context in stateless widget flutter code example

Example 1: flutter stateful widget

class YellowBird extends StatefulWidget {
  const YellowBird({ Key key }) : super(key: key);

  @override
  _YellowBirdState createState() => _YellowBirdState();
}

class _YellowBirdState extends State<YellowBird> {
  @override
  Widget build(BuildContext context) {
    return Container(color: const Color(0xFFFFE306));
  }
}

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 {

@override
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:

Misc Example