Isar does not persist state, every time I close my mobile application and open it again, previous values are not there, when they should be there. I'm fetching those values from Isar.
Please show with a counter app example how this works.
I'm attaching files.
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:isarapp/counter_schema.dart';
import 'package:isar/isar.dart';
import 'package:isarapp/home_screen.dart';
import 'package:path_provider/path_provider.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
var directory = await getApplicationDocumentsDirectory();
var path = directory.path;
await Isar.open(
[CounterObjectSchema],
directory: path,
inspector: true,
name: "isardb",
);
runApp(const MyApp());
}
class MyApp extends ConsumerWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context, WidgetRef ref) {
return ProviderScope(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const HomeScreen(),
),
);
}
}
I have edited android manifest file to get store permission then using permission_handler for getting storage access.
home_screen.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:isar/isar.dart';
import 'package:isarapp/counter_schema.dart';
import 'package:permission_handler/permission_handler.dart';
final counterProvider1 = StateProvider<int>((ref) {
return 0;
});
class HomeScreen extends ConsumerStatefulWidget {
const HomeScreen({super.key});
#override
ConsumerState<ConsumerStatefulWidget> createState() => _HomeScreenState();
}
getStoragePermission() async {
var status = await Permission.storage.status;
if (status.isDenied) {
Permission.storage.request();
}
}
class _HomeScreenState extends ConsumerState<HomeScreen> {
Isar? isar = Isar.getInstance("isardb");
CounterObject counterObject = CounterObject(counter: 9);
initCounter() async {
var count = await isar?.collection<CounterObject>().get(counterObject.id);
//reset counter on launch
ref.read(counterProvider1.notifier).state = count?.counter ?? -1;
}
increment() async {
counterObject.counter = counterObject.counter + 1;
//update state
ref.read(counterProvider1.notifier).state = counterObject.counter;
//writing counterValue to isardb on every increment call
isar?.writeTxn(
() async => await isar?.collection<CounterObject>().put(counterObject),
);
}//increment
#override
void initState() {
getStoragePermission();
//putting counterObject in
isar?.writeTxn(
() async => await isar?.counterObjects.put(counterObject),
);
initCounter();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
children: [
Text(
ref.watch(counterProvider1).toString(),
style: const TextStyle(fontSize: 54),
),
GestureDetector(
onTap: () => increment(),
child: Container(
width: 200,
height: 40,
color: Colors.blue[300],
child: const Center(child: Text("Add")),
),
),
],
),
),
),
);
}
}
CounterObjectSchema
import 'package:isar/isar.dart';
part 'counter_schema.g.dart';
#collection
class CounterObject {
Id id = Isar.autoIncrement;
int counter;
CounterObject({required this.counter});
}
Related
I have a serious problem with my Riverpod. Specifically, I am using StateProvider in Riverpod package. But when I update state, the widget tree does not rebuild. I checked the new state whether is updated by printing out state to see, I see that they are actually updated.
I have some same situations but when I click hot restart/reload page/scroll up,down mouse to change size chrome window, the widget tree rebuild one time.
Please help me and explain everything the most detail and easy to understand. Thank you very much
new state print out but UI not update
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:math';
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class Data {
final String data;
Data({required this.data});
}
final helloWorldProvider = StateProvider<Data?>((ref) => Data(data: 'No data'));
class MyApp extends ConsumerStatefulWidget {
const MyApp({super.key});
#override
ConsumerState<MyApp> createState() => _MyAppState();
}
class _MyAppState extends ConsumerState<MyApp> {
#override
void initState() {
// TODO: implement initState4
print("Init state");
super.initState();
// getData();
}
// getData() async {
// // http.Response response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
// // final title = jsonDecode(response.body)["title"];;
// // ref.read(helloWorldProvider.notifier).update((state) => title);
// SharedPreferences prefs = await SharedPreferences.getInstance();
// prefs.setString('valueTemp', 'newValue');
// String? valueTemp = prefs.getString('valueTemp');
// String value = valueTemp ?? '';
// Data data = Data(data: value);
// ref.read(helloWorldProvider.notifier).update((state) => data);
// print("Đã thực hiện xong");
// }
void _change() {
print("change");
final rawString = generateRandomString(5);
Data data = new Data(data: rawString);
ref.watch(helloWorldProvider.notifier).update((state) => data);
print(ref.read(helloWorldProvider.notifier).state?.data);
}
String generateRandomString(int len) {
var r = Random();
return String.fromCharCodes(List.generate(len, (index) => r.nextInt(33) + 89));
}
#override
Widget build(BuildContext context) {
print('Rebuild');
final data = ref.watch(helloWorldProvider.notifier).state;
final dataText = data?.data ?? 'No text';
print(dataText);
return MaterialApp(
title: 'Google Docs Clone',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Center(
child: Column(children: [
Text(dataText)
]
)
),
floatingActionButton: FloatingActionButton(
onPressed: _change,
tooltip: 'Change',
child: const Icon(Icons.add),
),
));
}
}
I don't want to use other pattern as Provider, Bloc, StateNotifierProvider, ChangeNotifierProvider... I only want to run StateProvider successfully. I have refered to many articles and stackoverflows answer but I did't found any useful helps to my case.
final data = ref.watch(helloWorldProvider.notifier).state;
is watching the notifier, which rarely changes. You want to watch the state change, as in:
final data = ref.watch(helloWorldProvider);
Fixed, Tested your code.
I recommend this article Flutter Riverpod 2.0: The Ultimate Guide to Advanced Riverpod 😀
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'dart:math';
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class Data {
final String data;
Data({required this.data});
}
final helloWorldProvider = StateProvider<Data?>((ref) => Data(data: 'No data'));
class MyApp extends ConsumerStatefulWidget {
const MyApp({super.key});
#override
ConsumerState<MyApp> createState() => _MyAppState();
}
class _MyAppState extends ConsumerState<MyApp> {
#override
void initState() {
// TODO: implement initState4
print("Init state");
super.initState();
// getData();
}
// getData() async {
// // http.Response response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
// // final title = jsonDecode(response.body)["title"];;
// // ref.read(helloWorldProvider.notifier).update((state) => title);
// SharedPreferences prefs = await SharedPreferences.getInstance();
// prefs.setString('valueTemp', 'newValue');
// String? valueTemp = prefs.getString('valueTemp');
// String value = valueTemp ?? '';
// Data data = Data(data: value);
// ref.read(helloWorldProvider.notifier).update((state) => data);
// print("Đã thực hiện xong");
// }
void _change() {
print("change");
final rawString = generateRandomString(5);
Data data = Data(data: rawString);
ref.read(helloWorldProvider.notifier).update((state) => data);
print(ref.read(helloWorldProvider.notifier).state?.data);
}
String generateRandomString(int len) {
var r = Random();
return String.fromCharCodes(
List.generate(len, (index) => r.nextInt(33) + 89));
}
#override
Widget build(BuildContext context) {
print('Rebuild');
final data = ref.watch(helloWorldProvider)?.data;
final dataText = data ?? 'No text';
print(dataText);
return MaterialApp(
title: 'Google Docs Clone',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Center(
child: Column(children: [Text(dataText)]),
),
floatingActionButton: FloatingActionButton(
onPressed: _change,
tooltip: 'Change',
child: const Icon(Icons.add),
),
),
);
}
}
I tried share package and it works but I want to add a Widget that only appears on the shared image, not on the app. So please help me this is the code so far:
import 'dart:ui';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:share/share.dart';
void main() {
runApp(MaterialApp(home: HomePage()));
}
class HomePage extends StatelessWidget {
final _contentKey = GlobalKey();
final bool forSharing;
HomePage({
Key key,
this.forSharing = false,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: const Icon(Icons.share),
onPressed: () => onTakeScreenShotAndSharing(
'Image',
_contentKey.currentContext,
),
),
],
),
body: RepaintBoundary(
key: _contentKey,
child: Column(
children: [
if (forSharing) Text('Text appear only for Sharing'), // This is the widget that I want it appear only on the shared image
Text('Content'),
],
),
),
);
}
void onTakeScreenShotAndSharing(String fileName, BuildContext context) async {
try {
RenderRepaintBoundary boundary = context.findRenderObject();
final image = await boundary?.toImage();
final bytes = await image?.toByteData(format: ImageByteFormat.png);
if (bytes == null || bytes.buffer == null) return;
final dir = (await getApplicationDocumentsDirectory()).path;
final file = File('$dir/$fileName${DateTime.now().toString()}.png');
final newFile = await file.writeAsBytes(bytes.buffer.asUint8List());
await Share.shareFiles([newFile.path]);
} catch (error) {
print(error);
}
}
}
i want to get data from open weather api, and i keep getting this:
NoSuchMethodError: The method '[]' was called on null.Reciever: null
tried calling:
is it a problem with the api or the code?the editor don't show any errors please help
my code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MaterialApp(
title: 'Weather',
home: Weather(),
));
}
String api_key = 'the key';
Future<List> fetchData() async {
var result = await http.get(Uri.http('http://api.openweathermap.org',
'weather?lat=15.53804515&lon=32.52674103&appid=$api_key&units=metric'));
return json.decode(result.body);
}
class Weather extends StatefulWidget {
#override
_WeatherState createState() => _WeatherState();
}
class _WeatherState extends State<Weather> {
Color bgcolor;
var data;
#override
void initState() {
super.initState();
fetchData().then((value) {
setState() {
data = value;
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue,
appBar: AppBar(
title: Text('Weather App'),
centerTitle: true,
),
body: Center(
child: Column(children: [
Text(data['main']['temp']),
Text(data['weather']['description']),
Text(data['name'])
]),
));
}
}
fetchData is asynchronous, meaning it will take some time to execute and fetch that weather data. Until then, the variable "data" is uninitialized and thus null. Try adding a check for if data is null, then return a loading page or CircularProgressIndicator.
Just add a simple null check -
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MaterialApp(
title: 'Weather',
home: Weather(),
));
}
String api_key = 'the key';
Future<List> fetchData() async {
var result = await http.get(Uri.http('http://api.openweathermap.org',
'weather?lat=15.53804515&lon=32.52674103&appid=$api_key&units=metric'));
return json.decode(result.body);
}
class Weather extends StatefulWidget {
#override
_WeatherState createState() => _WeatherState();
}
class _WeatherState extends State<Weather> {
Color bgcolor;
var data;
#override
void initState() {
super.initState();
fetchData().then((value) {
setState() {
data = value;
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue,
appBar: AppBar(
title: Text('Weather App'),
centerTitle: true,
),
body: Center(
child: data == null
? CircularProgressIndicator()
: Column(children: [
Text(data['main']['temp']),
Text(data['weather']['description']),
Text(data['name'])
]),
));
}
}
When I run main.dart on my real phone code runs without any mistakes, I can see the string value exactly on my Location page but when I adjust my android emulator phone's location Turkey/İstanbul it stuckes on spinner (Loading page), Spinner keeps turning forever so Location page never open, by the way "I/eatherforecast(19501): Waiting for a blocking GC ProfileSaver" error written on console. I really wonder the reason of this tedious issue. Have a nice day..
import 'package:flutter/material.dart';
import 'package:weatherforecast2/loadingpage.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark().copyWith(),
home: LoadingPage(),
);
}
}
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:weatherforecast2/locationpage.dart';
import 'locationfinder.dart';
import 'package:geolocator/geolocator.dart';
import 'network.dart';
class LoadingPage extends StatefulWidget {
static String id = "loadingpage";
#override
_LoadingPageState createState() => _LoadingPageState();
}
class _LoadingPageState extends State<LoadingPage> {
Map<String,dynamic> currentLocationWeatherData;
void initState(){
super.initState();
getDecodedCurrentLocationWeatherData();
}
void getDecodedCurrentLocationWeatherData()async{
Position position=await LocationFinder().getCurrentLocation();
currentLocationWeatherData = await NetworkHelper().getCurrentLocationWeather(position.latitude,
position.longitude);
Navigator.push(context, MaterialPageRoute(builder: (context) {
return LocationPage(
currentLocationWeatherData: currentLocationWeatherData,
);
}));
}
#override
Widget build(BuildContext context) {
return Container(
child: Center(
child:SpinKitFadingCube(
color: Colors.white,
size: 50,
),
),
);
}
}
import 'dart:convert';
import 'package:http/http.dart';
const String appid="57aad03f4e48ca815bb1184e74624f46";
const String openWeatherMapURL="https://api.openweathermap.org/data/2.5/weather";
class NetworkHelper{
Future<dynamic>getCurrentLocationWeather(lat,lon)async{
Response response=await get("https://api.openweathermap.org/data/2.5/weather?
lat=$lat&lon=$lon&appid=$appid");
if (response.statusCode == 200){
return jsonDecode(response.body);
}
}
}
import 'package:flutter/material.dart';
class LocationPage extends StatefulWidget {
LocationPage({#required this.currentLocationWeatherData});
final Map<String,dynamic> currentLocationWeatherData;
static String id = "locationpage";
#override
_LocationPageState createState() => _LocationPageState();
}
class _LocationPageState extends State<LocationPage> {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: Center(
child: Text(
widget.currentLocationWeatherData["weather"][0]["description"],
),
),
);
}
}
import 'package:geolocator/geolocator.dart';
class LocationFinder{
Future<Position> getCurrentLocation()async{
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
return position;
}
}
I made a function to fetch data from json file and I show that data to one page when ever my fetch function run it show an erorr for the time till Json fetch that is 3 to 4 second after that data fetch and show succesfully but that error show on screen is very awkward.
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(News1());
class News1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "Flutter",
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List data = [];
#override
void initState() {
fetchData();
super.initState();
}
void fetchData() async {
final response = await http.get('jsonfilelinkhere');
if (response.statusCode == 200) {
setState(() {
data = json.decode(response.body);
});
}
}
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
return Scaffold(
body: Padding(
padding: EdgeInsets.only(left: 50 ,right: 50),
child:ListView(
children: <Widget>[
Center(
child: Text(data[3]['Head']),
),
Center(
child: Text(data[0]['Description']),
),
Image.network(data[0]['ImgUrl']),
],
),
)
);
}
}
hope you got your answer. In case you can make a check that while your array is equal to null show CircularProgressIndicator(), else show data. If you are unable to do so I can share the code for you.
your fetchData() function is asynchronous, so your app tap the back of your function saying "hi, fetchData() start to work!!" but your app goes on minding its own job.
And you gave this job for it:
child: Text(data[3]['Head']),
so your app will hit this line of code while your data variable still is an empty list.
You have to prepare it for this situation. You can prepare the default value of the data or you can check if it's empty in the Widgets that depends on it.
You encountered that error as you displayed that data before it could actually load.
Use FutureBuilder to solve your issue.
Example code:
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(News1());
class News1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "Flutter",
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List data = [];
#override
void initState() {
fetchData();
super.initState();
}
Future<Map<String, dynamic>> fetchData() async {
final response = await http.get('jsonfilelinkhere');
if (response.statusCode == 200) {
setState(() {
return json.decode(response.body);
});
}
}
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
return Scaffold(
body: Padding(
padding: EdgeInsets.only(left: 50 ,right: 50),
child:FutureBuilder<Map<String, dynamic>>(
future: fetchData, // async work
builder: (context,snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting: return new Center(child: Text('Loading....'));
default:
if (snapshot.hasError)
return Text("Error!");
else{
data = snapshot.data;
return ListView(
children: <Widget>[
Center(
child: Text(data[3]['Head']),
),
Center(
child: Text(data[0]['Description']),
),
Image.network(data[0]['ImgUrl']),
],
)}
}
},
),
)
);
}
}