How to use flutter provider in a statefulWidget?

前端 未结 3 1351
礼貌的吻别
礼貌的吻别 2021-02-10 07:59

I am using flutter_provider for state management. I want to load some items on page(statefulwidget) load from Api. I am showing a loader on page start and want to show the items

3条回答
  •  我寻月下人不归
    2021-02-10 08:54

    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(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;
     }
    

    }

提交回复
热议问题