'Flutter using FutureProvider to get data from ChangeNotifier method
After implementing a simple ChangeNotifier i want to get data from one of this class method which that return a Future, but i can't define FutureProvider for this class, please see my code
main.dart:
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => Vpns(),
)
],
child: MaterialApp(
//...
home: SplashScreen(),
),
);
}
Vpns class:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_openvpn/flutter_openvpn.dart';
import 'package:http/http.dart' as http;
class Vpn with ChangeNotifier {
final String id;
final String name;
Vpn({
required this.id,
required this.name,
});
get speed => null;
}
class Vpns with ChangeNotifier {
late List<Vpn> _vpns;
List<Vpn> get vpns => [..._vpns];
//
set connectionState(String connectionState) {
_connectionState = connectionState;
notifyListeners();
}
late Vpn? _connectedVpn;
Vpn get connectedVpn => _connectedVpn!;
///
Future<void> fetchVpns() async {
List<Vpn> _newVpns = [];
///
notifyListeners();
}
///
}
as you can see i have a fetchVpns in Vpns class which i should use FutureProvider to get data from that. now how can i define in this sample code:
this below code is wrong and i should fix that
return Scaffold(
body: FutureProvider<Vpn>(
initialData: null,
builder: (_)=>Provider.of<Vpns>(context, listen: false).fetchVpns(),
child: ListView(
children: <Widget>[
///...
],
),
));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
