flutter provider stateless widget code example

Example 1: stateless widget flutter

class GreenFrog extends StatelessWidget {
  const GreenFrog({ Key key }) : super(key: key);

  
  Widget build(BuildContext context) {
    return Container(color: const Color(0xFF2DBD3A));
  }
}

Example 2: use provider on start in stateless widget

When using Provider for state management you don't need to use StatefullWidget, so how can you call a method of the ChangeNotifier on start of the app?

You can simply do that in the constructor of the ChangeNotifier, so that when you point out VideosProvider() to the ChangeNotifierProvider Builder the constructor will get called the first time the provider constructs the VideosProvider, so:

PlayList.dart:

class Playlist extends StatelessWidget {


Widget build(BuildContext context) {
  final videosState = Provider.of<VideosProvider>(context);
  var videos = videosState.playlist;
  return Scaffold(
    appBar: AppBar(
      title: Text('My Videos'),
    ),
    body: RefreshIndicator(
      child: Container(
        width: double.infinity,
        height: double.infinity,
        child: videos.length
            ? ListView.builder(
                itemBuilder: (BuildContext context, index) {
                  return _videoListItem(context, index, videos, videosState);
                },
                itemCount: videos.length,
              )
            : Center(
                child: CircularProgressIndicator(),
              ),
      ),
      onRefresh: () => null,
    ),
  );
} }

VideosProvider.dart:

class VideosProvider with ChangeNotifier {

  VideosProvider(){
    fetchVideosList();
  }

  List _playlist;
  int _currentVideoId;  
  get playlist => _playlist;

  void setPlayList(videosList) {
     _playlist = videosList;
  }

  Future fetchVideosList() async {
    http.Response response =
    await http.get("http://192.168.1.22:3000/videos-list/");

    print(json.decode(response.body));
    videos = json.decode(response.body)["data"];
    setPlayList(videos);
    return videos;
 }
}

Tags:

Dart Example