Image

flutter

Snippets

Snippets & example of code

3 min read
Last update: November 28, 2021

Pull to refresh

Example of feature pull to refresh by Muhammad Affan Khan, medium.com/@maffan/implementing-pull-to-refresh-in-flutter

lib/main.dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Pull to Refresh Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: UserList(),
    );
  }
}

class UserList extends StatefulWidget {
  
  State<StatefulWidget> createState() {
    return _UserListState();
  }
}

class _UserListState extends State<UserList> {
  final String apiUrl = "https://randomuser.me/api/?results=10";

  List<dynamic> _users = [];

  void fetchUsers() async {
    var result = await http.get(apiUrl);
    setState(() {
      _users = json.decode(result.body)['results'];
    });
  }

  String _name(dynamic user) {
    return user['name']['title'] +
        " " +
        user['name']['first'] +
        " " +
        user['name']['last'];
  }

  String _location(dynamic user) {
    return user['location']['country'];
  }

  String _age(Map<dynamic, dynamic> user) {
    return "Age: " + user['dob']['age'].toString();
  }

  Widget _buildList() {
    return _users.length != 0
        ? RefreshIndicator(
            child: ListView.builder(
                padding: EdgeInsets.all(8),
                itemCount: _users.length,
                itemBuilder: (BuildContext context, int index) {
                  return Card(
                    child: Column(
                      children: <Widget>[
                        ListTile(
                          leading: CircleAvatar(
                              radius: 30,
                              backgroundImage: NetworkImage(
                                  _users[index]['picture']['large'])),
                          title: Text(_name(_users[index])),
                          subtitle: Text(_location(_users[index])),
                          trailing: Text(_age(_users[index])),
                        )
                      ],
                    ),
                  );
                }),
            onRefresh: _getData,
          )
        : Center(child: CircularProgressIndicator());
  }

  Future<void> _getData() async {
    setState(() {
      fetchUsers();
    });
  }

  
  void initState() {
    super.initState();
    fetchUsers();
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('User List'),
      ),
      body: Container(
        child: _buildList(),
      ),
    );
  }
}

TabBar & BottomBar

stackoverflow.com by Rainer Wittmann

android-versions

lib/main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  
  State createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  TabController _controller;
  int _index;

  
  void initState() {
    super.initState();
    _controller = new TabController(length: 4, vsync: this);
    _index = 0;
  }

  
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Traveler"),
        bottom: new TabBar(controller: _controller, tabs: <Tab>[
          new Tab(text: "NEW"),
          new Tab(text: "HOTELS"),
          new Tab(text: "FOOD"),
          new Tab(text: "FUN"),
        ]),
      ),
      body: new TabBarView(
        controller: _controller,
        children: <Widget>[
          new NewPage(_index),
          new HotelsPage(_index),
          new FoodPage(_index),
          new FunPage(_index),
        ],
      ),
      bottomNavigationBar: new BottomNavigationBar(
          currentIndex: _index,
          onTap: (int _index) {
            setState(() {
              this._index = _index;
            });
          },
          items: <BottomNavigationBarItem>[
            new BottomNavigationBarItem(
              icon: new Icon(Icons.home),
              title: new Text("Home"),
            ),
            new BottomNavigationBarItem(
              icon: new Icon(Icons.favorite),
              title: new Text("Favorites"),
            ),
          ]),
    );
  }
}

class NewPage extends StatelessWidget {
  final int index;

  NewPage(this.index);

  
  Widget build(BuildContext context) {
    return new Center(
      child: new Text('NewPage, index: $index'),
    );
  }
}

class HotelsPage extends StatelessWidget {
  final int index;

  HotelsPage(this.index);

  
  Widget build(BuildContext context) {
    return new Center(
      child: new Text('HotelsPage, index: $index'),
    );
  }
}

class FoodPage extends StatelessWidget {
  final int index;

  FoodPage(this.index);

  
  Widget build(BuildContext context) {
    return new Center(
      child: new Text('FoodPage, index: $index'),
    );
  }
}

class FunPage extends StatelessWidget {
  final int index;

  FunPage(this.index);

  
  Widget build(BuildContext context) {
    return new Center(
      child: new Text('FunPage, index: $index'),
    );
  }
}

Swipeable bottomNavigationBar

medium.com/@uncoded_decimal

lib/tab_layout.dart
import 'package:flutter/material.dart';

class TabLayoutDemo extends StatelessWidget {
  
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
      color: Colors.yellow,
      home: DefaultTabController(
        length: 4,
        child: new Scaffold(
          body: TabBarView(
            children: [
              new Container(
                color: Colors.yellow,
              ),
              new Container(color: Colors.orange,),
              new Container(
                color: Colors.lightGreen,
              ),
              new Container(
                color: Colors.red,
              ),
            ],
          ),
          bottomNavigationBar: new TabBar(
            tabs: [
              Tab(
                icon: new Icon(Icons.home),
              ),
              Tab(
                icon: new Icon(Icons.rss_feed),
              ),
              Tab(
                icon: new Icon(Icons.perm_identity),
              ),
              Tab(icon: new Icon(Icons.settings),)
            ],
            labelColor: Colors.yellow,
            unselectedLabelColor: Colors.blue,
            indicatorSize: TabBarIndicatorSize.label,
            indicatorPadding: EdgeInsets.all(5.0),
            indicatorColor: Colors.red,
          ),
          backgroundColor: Colors.black,
        ),
      ),
    );
  }
}