Category: Examples

https://cdn-icons-png.flaticon.com/512/5307/5307812.png

  • Implementing a Bottom Sheet

    This example demonstrates how to show a bottom sheet with options when a button is pressed.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
    
    return MaterialApp(
      title: 'Bottom Sheet Example',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: BottomSheetExample(),
    );
    } } class BottomSheetExample extends StatelessWidget { void _showBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return Container(
          padding: EdgeInsets.all(16.0),
          height: 200,
          child: Column(
            children: [
              Text('Select an option', style: TextStyle(fontSize: 18)),
              ListTile(
                title: Text('Option 1'),
                onTap: () {
                  Navigator.pop(context);
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Selected Option 1')),
                  );
                },
              ),
              ListTile(
                title: Text('Option 2'),
                onTap: () {
                  Navigator.pop(context);
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Selected Option 2')),
                  );
                },
              ),
            ],
          ),
        );
      },
    );
    } @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Bottom Sheet Example')),
      body: Center(
        child: ElevatedButton(
          onPressed: () => _showBottomSheet(context),
          child: Text('Show Bottom Sheet'),
        ),
      ),
    );
    } }
  • Using a TabBar for Navigation

    This example shows how to use a TabBar for navigating between different sections of an app.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
    
    return MaterialApp(
      title: 'TabBar Example',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: TabBarExample(),
    );
    } } class TabBarExample extends StatelessWidget { @override Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          title: Text('TabBar Example'),
          bottom: TabBar(
            tabs: [
              Tab(text: 'Home'),
              Tab(text: 'Search'),
              Tab(text: 'Profile'),
            ],
          ),
        ),
        body: TabBarView(
          children: [
            Center(child: Text('Home Screen')),
            Center(child: Text('Search Screen')),
            Center(child: Text('Profile Screen')),
          ],
        ),
      ),
    );
    } }
  • Displaying Data in a Grid View

    This example illustrates how to create a grid layout to display images or items.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
    
    return MaterialApp(
      title: 'Grid View Example',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: GridViewExample(),
    );
    } } class GridViewExample extends StatelessWidget { final List<String> _images = [
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/150',
    ]; @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Grid View Example')),
      body: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 1,
        ),
        itemCount: _images.length,
        itemBuilder: (context, index) {
          return Card(
            child: Image.network(
              _images&#91;index],
              fit: BoxFit.cover,
            ),
          );
        },
      ),
    );
    } }
  • Implementing a Search Functionality

    This example shows how to create a search feature using a TextField to filter a list of items.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
    
    return MaterialApp(
      title: 'Search Example',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: SearchExample(),
    );
    } } class SearchExample extends StatefulWidget { @override _SearchExampleState createState() => _SearchExampleState(); } class _SearchExampleState extends State<SearchExample> { final List<String> _items = [
    'Apple',
    'Banana',
    'Cherry',
    'Date',
    'Fig',
    'Grapes',
    'Orange',
    'Peach',
    'Pineapple',
    'Strawberry',
    ]; List<String> _filteredItems = []; String _searchQuery = ''; @override void initState() {
    super.initState();
    _filteredItems = _items;
    } void _filterItems(String query) {
    if (query.isNotEmpty) {
      setState(() {
        _searchQuery = query;
        _filteredItems = _items
            .where((item) => item.toLowerCase().contains(query.toLowerCase()))
            .toList();
      });
    } else {
      setState(() {
        _searchQuery = '';
        _filteredItems = _items;
      });
    }
    } @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Search Example')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: &#91;
            TextField(
              onChanged: _filterItems,
              decoration: InputDecoration(
                labelText: 'Search',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 10),
            Expanded(
              child: ListView.builder(
                itemCount: _filteredItems.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(_filteredItems&#91;index]),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
    } }
  • Creating a Custom SnackBar

    This example demonstrates how to create and display a custom SnackBar with actions.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
    
    return MaterialApp(
      title: 'Custom SnackBar',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: SnackBarExample(),
    );
    } } class SnackBarExample extends StatelessWidget { void _showSnackBar(BuildContext context) {
    final snackBar = SnackBar(
      content: Text('This is a custom SnackBar!'),
      action: SnackBarAction(
        label: 'Undo',
        onPressed: () {
          // Undo action
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Action undone!')),
          );
        },
      ),
      duration: Duration(seconds: 3),
    );
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
    } @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Custom SnackBar')),
      body: Center(
        child: ElevatedButton(
          onPressed: () => _showSnackBar(context),
          child: Text('Show SnackBar'),
        ),
      ),
    );
    } }
  • Fetching and Displaying Images from the Network

    This example shows how to fetch and display images from the internet.

    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
    
    return MaterialApp(
      title: 'Image Fetch Example',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: ImageList(),
    );
    } } class ImageList extends StatefulWidget { @override _ImageListState createState() => _ImageListState(); } class _ImageListState extends State<ImageList> { List _images = []; bool _loading = true; @override void initState() {
    super.initState();
    _fetchImages();
    } Future<void> _fetchImages() async {
    final response = await http.get(Uri.parse('https://api.example.com/images'));
    if (response.statusCode == 200) {
      setState(() {
        _images = json.decode(response.body);
        _loading = false;
      });
    } else {
      throw Exception('Failed to load images');
    }
    } @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Image Fetch Example')),
      body: _loading
          ? Center(child: CircularProgressIndicator())
          : GridView.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
              itemCount: _images.length,
              itemBuilder: (context, index) {
                return Image.network(_images&#91;index]&#91;'url']);
              },
            ),
    );
    } }
  • Using Provider for State Management

    This example demonstrates how to use the Provider package for state management in a Flutter app.

    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    
    void main() {
      runApp(
    
    ChangeNotifierProvider(
      create: (context) => Counter(),
      child: MyApp(),
    ),
    ); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Provider Example',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: CounterScreen(),
    );
    } } class Counter with ChangeNotifier { int _count = 0; int get count => _count; void increment() {
    _count++;
    notifyListeners();
    } void decrement() {
    _count--;
    notifyListeners();
    } } class CounterScreen extends StatelessWidget { @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Counter')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: &#91;
            Text('Count: ${context.watch&lt;Counter>().count}'),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: &#91;
                ElevatedButton(
                  onPressed: () => context.read&lt;Counter>().decrement(),
                  child: Text('-'),
                ),
                SizedBox(width: 20),
                ElevatedButton(
                  onPressed: () => context.read&lt;Counter>().increment(),
                  child: Text('+'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
    } }
  • Using a Drawer for Navigation

    This example showcases how to implement a navigation drawer in a Flutter application.

    dartCopy codeimport 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
    
    return MaterialApp(
      title: 'Drawer Navigation',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: HomeScreen(),
    );
    } } class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Drawer Navigation')),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: &#91;
            DrawerHeader(
              decoration: BoxDecoration(color: Colors.blue),
              child: Text(
                'Navigation',
                style: TextStyle(color: Colors.white, fontSize: 24),
              ),
            ),
            ListTile(
              title: Text('Home'),
              onTap: () {
                Navigator.pop(context); // Close the drawer
              },
            ),
            ListTile(
              title: Text('Settings'),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) =&gt; SettingsScreen()),
                );
              },
            ),
          ],
        ),
      ),
      body: Center(child: Text('Home Screen')),
    );
    } } class SettingsScreen extends StatelessWidget { @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Settings')),
      body: Center(child: Text('Settings Screen')),
    );
    } }
  • Form Validation Example

    This example demonstrates how to create a form with validation using TextFormField and GlobalKey.

    dartCopy codeimport 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
    
    return MaterialApp(
      title: 'Form Validation',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: RegistrationForm(),
    );
    } } class RegistrationForm extends StatefulWidget { @override _RegistrationFormState createState() => _RegistrationFormState(); } class _RegistrationFormState extends State<RegistrationForm> { final _formKey = GlobalKey<FormState>(); String? _name; String? _email; @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Registration Form')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: &#91;
              TextFormField(
                decoration: InputDecoration(labelText: 'Name'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your name';
                  }
                  return null;
                },
                onSaved: (value) =&gt; _name = value,
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Email'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your email';
                  } else if (!RegExp(r'^&#91;^@]+@&#91;^@]+\.&#91;^@]+').hasMatch(value)) {
                    return 'Please enter a valid email';
                  }
                  return null;
                },
                onSaved: (value) =&gt; _email = value,
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    _formKey.currentState!.save();
                    // Process the data
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('Name: $_name, Email: $_email')),
                    );
                  }
                },
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
    } }
  • Implementing Navigation with Bottom Navigation Bar

    This example shows how to set up a basic app with a Bottom Navigation Bar to switch between different screens.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
    
    return MaterialApp(
      title: 'Bottom Navigation',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: MainScreen(),
    );
    } } class MainScreen extends StatefulWidget { @override _MainScreenState createState() => _MainScreenState(); } class _MainScreenState extends State<MainScreen> { int _currentIndex = 0; final List<Widget> _screens = [
    Screen1(),
    Screen2(),
    Screen3(),
    ]; void _onItemTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
    } @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Bottom Navigation')),
      body: _screens&#91;_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        items: const &lt;BottomNavigationBarItem>&#91;
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
          BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'),
        ],
        currentIndex: _currentIndex,
        onTap: _onItemTapped,
      ),
    );
    } } class Screen1 extends StatelessWidget { @override Widget build(BuildContext context) {
    return Center(child: Text('Home Screen'));
    } } class Screen2 extends StatelessWidget { @override Widget build(BuildContext context) {
    return Center(child: Text('Search Screen'));
    } } class Screen3 extends StatelessWidget { @override Widget build(BuildContext context) {
    return Center(child: Text('Profile Screen'));
    } }