Flutter package lateintialization error - '_image' has not been initialized - flutter

I'm trying to make the image_editor_pro package in flutter to work using their example, but when I run the app, I get a lateintialization error '_image' has not been initialized , I tried replacing late with ? , but then I got another error since File type can't allow null values
The code :
import 'dart:io';
import 'package:image_editor_pro/image_editor_pro.dart';
import 'package:firexcode/firexcode.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return HomePage().xMaterialApp();
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late File _image;
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.black87,
bottomBarColor: Colors.black87,
pathSave: null,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _image == null,
isTrue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse:
_image == null ? Container() : Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
Widget condition(
{required bool condtion, required Widget isTrue, required Widget isFalse}) {
return condtion ? isTrue : isFalse;
}

You could use a boolean to check if _image has been initialized:
class _HomePageState extends State<HomePage> {
late File _image;
bool _isImageInitialized = false;
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.black87,
bottomBarColor: Colors.black87,
pathSave: null,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
_isImageInitialized = true;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _isImageInitialized == false,
isTrue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse:
Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}

Instead of using late File _image; you can use File? _image; which makes the _image variable nullable with default value null. Make sure to have proper null checks like (_image != null ) or (image?.method)
Full Code
import 'dart:io';
import 'package:image_editor_pro/image_editor_pro.dart';
import 'package:firexcode/firexcode.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return HomePage().xMaterialApp();
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File? _image;
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.black87,
bottomBarColor: Colors.black87,
pathSave: null,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _image == null,
isTrue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse:
_image == null ? Container() : Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
Widget condition(
{required bool condtion, required Widget isTrue, required Widget isFalse}) {
return condtion ? isTrue : isFalse;
}

Related

flutter does not show data from API

When I try to pull data from the jsonplaceholder API and put it on the screen, I don't have any problems, but when I try to change the data in this link (https://reqres.in/api/users?page=2 ) on the reqres.io site with the same codes, only by changing the API and model, the text no data appears on the screen. I'm getting it can you help me ?
My project with JsonPlaceHolder
main.dart
import 'package:flutter/material.dart';
import 'package:my_app/models/json_model.dart';
import 'service/api_service.dart';
void main() =\> runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: const Text('Json Deneme'),
),
body: const Home(),
),
);
}
}
class Home extends StatefulWidget {
const Home({super.key});
#override
State\<Home\> createState() =\> \_HomeState();
}
class \_HomeState extends State\<Home\> {
List\<JsonModel\>? \_postItems;
bool \_isLoading = false;
String? \_errorMessage;
#override
void initState() {
super.initState();
loadData();
}
Future\<void\> loadData() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final postItems = await Api.fetchApi();
setState(() {
_postItems = postItems;
_isLoading = false;
});
} catch (e) {
setState(() {
_isLoading = false;
_errorMessage = 'Error fetching data: $e';
});
}
}
#override
Widget build(BuildContext context) {
if (\_isLoading) {
return const Center(child: CircularProgressIndicator());
} else if (\_postItems == null || \_postItems!.isEmpty) {
return const Center(child: Text('No Data'));
} else {
return ListView.builder(
itemCount: \_postItems!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(\_postItems!\[index\].name),
);
},
);
}
}
}`
api_service.dart
`import 'dart:io';
import 'package:my_app/models/json_model.dart';
import 'package:dio/dio.dart';
class Api {
static Future<List<JsonModel>?> fetchApi() async {
final res = await Dio().get("https://jsonplaceholder.typicode.com/users");
if (res.statusCode == HttpStatus.ok) {
final data = res.data!;
if (data is List) {
return data.map((e) =\> JsonModel.fromMap(e)).toList();
}
}
return <JsonModel>[];
}
}
`
conclusion
conclusion
My project with reqres.in
main.dart
`import 'package:flutter/material.dart';
import 'package:my_app/models/json_model.dart';
import 'service/api_service.dart';
void main() =\> runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: const Text('Json Deneme'),
),
body: const Home(),
),
);
}
}
class Home extends StatefulWidget {
const Home({super.key});
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<ReqresModel>? _postItems;
bool _isLoading = false;
String? _errorMessage;
#override
void initState() {
super.initState();
loadData();
}
Future<void> loadData() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final postItems = await Api.fetchApi();
setState(() {
_postItems = postItems;
_isLoading = false;
});
} catch (e) {
setState(() {
_isLoading = false;
_errorMessage = 'Error fetching data: $e';
});
}
}
#override
Widget build(BuildContext context) {
if (_isLoading) {
return const Center(child: CircularProgressIndicator());
} else if (_postItems == null || _postItems!.isEmpty) {
return const Center(child: Text('No Data'));
} else {
return ListView.builder(
itemCount: _postItems!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(\_postItems!\[index\].data\[index\].firstName),
);
},
);
}
}
}`
api_servise.dart
`import 'dart:io';
import 'package:my_app/models/json_model.dart';
import 'package:dio/dio.dart';
class Api {
static Future<List<ReqresModel>?> fetchApi() async {
final res = await Dio().get("https://reqres.in/api/users?page=2");
if (res.statusCode == HttpStatus.ok) {
final data = res.data!;
if (data is List) {
return data.map((e) => ReqresModel.fromMap(e)).toList();
}
}
return <ReqresModel>[];
}
}`
conclusion
conclusion
**Thank you **
I sent the API using Postman, there was no problem, I don't think the problem was caused by the API, sorry for my bad English
Change your api_service.dart for reqres.in project with following code.
First api which returns List directly, but second api which return Json which has data as List
Edited
main.dart
import 'package:flutter/material.dart';
import 'package:my_app/models/json_model.dart';
import 'service/api_service.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: const Text('Json Deneme'),
),
body: const Home(),
),
);
}
}
class Home extends StatefulWidget {
const Home({super.key});
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<ReqresModel>? _postItems;
bool _isLoading = false;
String? _errorMessage;
#override
void initState() {
super.initState();
loadData();
}
Future<void> loadData() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final postItems = await Api.fetchApi();
setState(() {
_postItems = postItems;
_isLoading = false;
});
} catch (e) {
setState(() {
_isLoading = false;
_errorMessage = 'Error fetching data: $e';
});
}
}
#override
Widget build(BuildContext context) {
if (_isLoading) {
return const Center(child: CircularProgressIndicator());
} else if (_postItems == null || _postItems!.isEmpty) {
return const Center(child: Text('No Data'));
} else {
return ListView.builder(
itemCount: _postItems!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_postItems![index].firstName),//Updated here
);
},
);
}
}
}
api_service.dart
import 'dart:io';
import 'package:my_app/models/json_model.dart';
import 'package:dio/dio.dart';
class Api {
static Future<List<ReqresModel>?> fetchApi() async {
final res = await Dio().get("https://reqres.in/api/users?page=2");
if (res.statusCode == HttpStatus.ok) {
final data = res.data!['data'];//Updated here
if (data is List) {
return data.map((e) => ReqresModel.fromMap(e)).toList();
}
}
return <ReqresModel>[];
}
}
ReqresModel - should be updated
//Updated here
class ReqresModel {
int? id;
String? email;
String? firstName;
String? lastName;
String? avatar;
ReqresModel(
{this.id, this.email, this.firstName, this.lastName, this.avatar});
ReqresModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
email = json['email'];
firstName = json['first_name'];
lastName = json['last_name'];
avatar = json['avatar'];
}
}

The await expression can only be used in an async function. Although there is async in this function in Flutter/Dart

I have an asynchronous function for checking internet access which is in another file. Here is its code:
//Check User Connection
class CheckUserConnection {
Future checkInternetAvailability() async {
try {
final result = await InternetAddress.lookup('example.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
return true;
}
} on SocketException catch (_) {
return false;
}
}
}
I need it to be activated when a button is pressed in the main menu. Here is the code for this screen:
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Example';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Container(
child: Scaffold(
appBar: AppBar(title: const Text(_title)),
// body: const MyStatelessWidget(),
body: const MainWidget(),
),
)
);
}
}
// class MyStatelessWidget extends StatelessWidget {
// const MyStatelessWidget({Key? key}) : super(key: key);
class MainWidget extends StatefulWidget {
const MainWidget({Key? key}) : super(key: key);
#override
State<MainWidget> createState() => _MainWidgetState();
}
class _MainWidgetState extends State<MainWidget> {
#override
Widget build(BuildContext context) {
InternetDialogHandler _internetDialogHandler = InternetDialogHandler();
CheckUserConnection _checkUserConnection = CheckUserConnection();
bool _internetAvailable = await _checkUserConnection.checkInternetAvailability();
// bool _internetAvailable = false;
return Center(
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
children: [
GradientButton(label: 'New Game', onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const NewGameRoute()),
);
}),
GradientButton(label: 'Continue Game', onTap: () {
if(_internetAvailable)
{
//do something here;
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const NewGameRoute()),
);
} else{
//handle no internet here
_internetDialogHandler.showInternetDialog(context);
}
}),
],
),
Column(
children: [
GradientButton(label: 'Back Button', onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const BackRoute()),
);
// print('Button 1');
}),
GradientButton(label: 'Button 2', onTap: () {print('Button 2');}),
GradientButton(label: 'Internet', onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const InternetRoute()),
);
}),
],
)
],
),
);
}
}
But the problem is that when I paste:
bool _internetAvailable = await _checkUserConnection.checkInternetAvailability();
I get an error:
The await expression can only be used in an async function.
Why? Async is already in that function, which is in another file. Where else do I need to add async in my main page code?
I've been given advice:
In initstate just call a method. And in that method add async and check internrt and set state based on internet availability
But since I'm a beginner, I don't understand what exactly I should do.
Edit1. This code does not throw any errors:
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Example';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Container(
child: Scaffold(
appBar: AppBar(title: const Text(_title)),
// body: const MyStatelessWidget(),
body: const MainWidget(),
),
)
);
}
}
// class MyStatelessWidget extends StatelessWidget {
// const MyStatelessWidget({Key? key}) : super(key: key);
class MainWidget extends StatefulWidget {
const MainWidget({Key? key}) : super(key: key);
#override
State<MainWidget> createState() => _MainWidgetState();
}
class _MainWidgetState extends State<MainWidget> {
CheckUserConnection _checkUserConnection = CheckUserConnection();
bool? _internetAvailable;
void checkNet() async{
_internetAvailable = await
_checkUserConnection.checkInternetAvailability();
// can you do any async operation into this method, Just be careful to check it
}
#override
void initState(){
super.initState();
checkNet();
}
#override
Widget build(BuildContext context) {
InternetDialogHandler _internetDialogHandler = InternetDialogHandler();
// CheckUserConnection _checkUserConnection = CheckUserConnection();
// bool _internetAvailable = await _checkUserConnection.checkInternetAvailability();
// bool _internetAvailable = false;
return Center(
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
children: [
GradientButton(label: 'New Game', onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const NewGameRoute()),
);
}),
GradientButton(label: 'Continue Game', onTap: () {
// if(_internetAvailable)
// {
// //do something here;
// Navigator.push(
// context,
// MaterialPageRoute(builder: (context) => const NewGameRoute()),
// );
// } else{
// //handle no internet here
// _internetDialogHandler.showInternetDialog(context);
// }
return _internetAvailable == null?
_internetDialogHandler.showInternetDialog(context)
:
print('_internetAvailable = null');
}),
],
),
Column(
children: [
GradientButton(label: 'Back Button', onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const BackRoute()),
);
// print('Button 1');
}),
GradientButton(label: 'Button 2', onTap: () {print('Button 2');}),
GradientButton(label: 'Internet', onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const InternetRoute()),
);
}),
],
)
],
),
);
}
}
But the problem is that _internetAvailable returns null regardless of the Internet connection.
Edi2. Trying Kaushik Chandru's code:
class _MainWidgetState extends State<MainWidget> {
InternetDialogHandler _internetDialogHandler = InternetDialogHandler();
CheckUserConnection _checkUserConnection = CheckUserConnection();
#override
void initState(){
super.initState();
checkInternet((){
//Add what to do if internet is available
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const NewGameRoute()),
);
},
(){
//Add what to do if no internet
_internetDialogHandler.showInternetDialog(context);
}
);
}
checkInternet(Function? ifAvailable, Function? ifUnavailable) async{
bool internetAvailable = await _checkUserConnection.checkInternetAvailability();
if(internetAvailable)
{
ifAvailable();
}
else{
ifUnavailable();
}
}
#override
Widget build(BuildContext context) {
...
I have this error:
88:18: Error: Can't use an expression of type 'Function?' as a function because it's potentially null.
- 'Function' is from 'dart:core'.
Try calling using ?.call instead.
ifAvailable();
^
lib/main.dart:91:20: Error: Can't use an expression of type 'Function?' as a function because it's potentially null.
- 'Function' is from 'dart:core'.
Try calling using ?.call instead.
ifUnavailable();
^
Edit3. For Kaushik Chandru only
lib/main.dart:92:21: Error: Expected an identifier, but got ';'.
Try inserting an identifier before ';'.
ifAvailable()?;
^
lib/main.dart:92:21: Error: Expected ':' before this.
ifAvailable()?;
^
lib/main.dart:95:23: Error: Expected an identifier, but got ';'.
Try inserting an identifier before ';'.
ifUnavailable()?;
^
lib/main.dart:95:23: Error: Expected ':' before this.
ifUnavailable()?;
^
lib/main.dart:92:18: Error: Can't use an expression of type 'Function?' as a function because it's potentially null.
- 'Function' is from 'dart:core'.
Try calling using ?.call instead.
ifAvailable()?;
^
lib/main.dart:95:20: Error: Can't use an expression of type 'Function?' as a function because it's potentially null.
- 'Function' is from 'dart:core'.
Try calling using ?.call instead.
ifUnavailable()?;
^
Edit4 for Hossein Asadi. Just in case, I added the print in different places, tried different options. But there is no such entry in the console. When I click on my button, the condition that _internetAvailable == null is triggered.
class _MainWidgetState extends State<MainWidget> {
CheckUserConnection _checkUserConnection = CheckUserConnection();
bool? _internetAvailable;
void checkNet() async{
_internetAvailable = await
_checkUserConnection.checkInternetAvailability();
print("ok");
setState((){});
// can you do any async operation into this method, Just be careful to check it
}
#override
void initState(){
super.initState();
checkNet();
print("ok");
}
Add an initstate to the stateful widget. Inside the initstate add this code
checkInternet((){
//Add what to do if internet is available
},
(){
//Add what to do if no internet
}
);
Then define a function
checkInternet(VoidCallback ifAvailable, VoidCallback ifUnavailable) async{
bool internetAvaibale = await _checkInternetConnection.checkInternetAvailability();
if(internetAvailable)
{
ifAvailable();
}
else{
ifUnavailable();
}
}
you called bool _internetAvailable = await _checkUserConnection.checkInternetAvailability(); in build method, In the event that build method can't be async.
you must be do like below code:
class _MainWidgetState extends State<MainWidget> {
bool? _internetAvailable;
void checkNet() async{
_internetAvailable = await
_checkUserConnection.checkInternetAvailability();
setState((){});
// can you do any async operation into this method, Just be careful to check it
}
#overrider
void initState(){
super.initState();
checkNet();
}
#override
Widget build(BuildContext context) {
....
return _internetAvailable == null?
CupertinoActivityIndicator()//loading
:Center(
child: Column(
....

How to properly initialize variables with Localization?

I've followed a lot of tutorials and optimized the localization as much as possible.
The problem here is that the variables aren't properly initialized. First instance it shows errors of variables not being initialized. I then do a hot reload without changing anything. Now it rebuilds and then I navigated to the settings page to change the language and it did updated the strings.
So my main issue here is why are my variables not being initialized at first instance?
main.dart:
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) => ChangeNotifierProvider(
create: (context) => LocaleProvider(),
builder: (context, child) {
final provider = Provider.of<LocaleProvider>(context).locale;
return ThemeProvider(
saveThemesOnChange: true,
loadThemeOnInit: true,
child: LayoutBuilder(builder: (context, constraints) {
return OrientationBuilder(builder: (context, orientation) {
SizeConfig().init(constraints, orientation);
return MaterialApp(
theme: CustomTheme.lightTheme,
debugShowCheckedModeBanner: false,
routes: <String, WidgetBuilder>{
'/splash': (BuildContext context) =>
const SplashPortrait(),
},
locale: provider,
localizationsDelegates:
AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: ThemeConsumer(
child: orientation == Orientation.portrait
? const SplashPortrait()
: const SplashLandscape(),
),
);
});
}));
},
);
}
class SplashPortrait extends StatefulWidget {
const SplashPortrait({Key? key}) : super(key: key);
#override
State<SplashPortrait> createState() => _SplashPortraitState();
}
class _SplashPortraitState extends State<SplashPortrait>
with TickerProviderStateMixin {
late SharedPreferences sharedPreferences;
#override
void initState() {
super.initState();
init();
}
Future init() async {
sharedPreferences = await SharedPreferences.getInstance();
final rememberMe = sharedPreferences.getBool("rememberMe");
if (rememberMe != null) {
if (rememberMe) {
final profile = sharedPreferences.getString("currentUser");
if (profile == null) return;
Constants.currentProfile = Profile.fromJson(json.decode(profile));
Constants.token = sharedPreferences.getString("token")!;
Constants.headers = {
"Content-Type": 'application/json',
"x-access-token": Constants.token,
};
Future.delayed(const Duration(milliseconds: 4000), () {
Navigator.of(context)
.push(SlideRightRoute(page: const HomeScreen(fragmentIndex: 0)));
});
} else {
Future.delayed(const Duration(milliseconds: 4000), () {
Navigator.of(context)
.push(SlideRightRoute(page: const LoginScreen()));
});
}
} else {
Future.delayed(const Duration(milliseconds: 4000), () {
Navigator.of(context).push(SlideRightRoute(page: const LoginScreen()));
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: SizedBox(
width: MediaQuery.of(context).size.width / 2,
child: const RiveAnimation.asset(
'assets/splash.riv',
),
),
),
);
}
}
Login Page is where I am experiencing errors:
class LoginScreen extends StatefulWidget {
const LoginScreen({
Key? key,
}) : super(key: key);
#override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
late LoginBloc loginBloc;
FocusNode emailFocus = FocusNode();
FocusNode passwordFocus = FocusNode();
late TextEditingController emailController;
late TextEditingController passwordController;
late bool isPasswordVisible;
late String emailHint;
late String passwordHint;
late bool rememberMe;
#override
void initState() {
super.initState();
init();
}
init() {
emailController = TextEditingController();
passwordController = TextEditingController();
emailHint = context.loc.emailPlaceholder;
passwordHint = context.loc.passwordPlaceholder;
emailFocus.addListener(onEmailFocusChanged);
passwordFocus.addListener(onPasswordFocusChanged);
isPasswordVisible = false;
rememberMe = false;
loginBloc = LoginBloc(context: context, rememberMe: false);
}
void onEmailFocusChanged() {
if (emailFocus.hasFocus) {
setState(() {
emailHint = "";
});
} else {
setState(() {
emailHint = context.loc.emailPlaceholder;
});
}
}
void onPasswordFocusChanged() {
if (passwordFocus.hasFocus) {
setState(() {
passwordHint = "";
});
} else {
setState(() {
passwordHint = context.loc.passwordPlaceholder;
});
}
}
#override
void dispose() {
loginBloc.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: colorWhite,
body: SafeArea(
child: WillPopScope(
child: LoginPortrait(context),
onWillPop: () => onWillPop(),
)),
);
}
onWillPop() {
SystemNavigator.pop();
}
context.loc.
extension LocalizedBuildContext on BuildContext {
AppLocalizations get loc => AppLocalizations.of(this);
}
Solutions I've tried:
1.) Future.delayed
2.) WidgetsBinding.instance?.addPostFrameCallback
3.) SchedulerBinding.instance!.addPostFrameCallback
4.) didChangeDependencies()

How to send the fetched data everytime to some other widget in Flutter

Wanted to pass the updated values of fetchedEntriesInApp to PasswdList widget everytime it loads.
Below is my code.
main.dart
Future fetchEntries() async {
var fetchedEntries = [];
var db = FirebaseFirestore.instance;
final res = await db.collection("password_entries").get().then((event) {
for (var doc in event.docs) {
var resDic = {
"entry_id": doc.id,
"data": doc.data(),
};
fetchedEntries.add(resDic);
}
});
return fetchedEntries;
}
class Body extends StatefulWidget {
#override
State<Body> createState() => _BodyState();
}
class _BodyState extends State<Body> {
late Future fetchedEntriesInApp;
#override
void initState() {
super.initState();
fetchedEntriesInApp = fetchEntries();
}
void refreshEntries() {
setState(() {
fetchedEntriesInApp = fetchEntries();
});
}
#override
Widget build(BuildContext context) {
setState(() {});
return FutureBuilder(
future: fetchedEntriesInApp!,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Text('Loading');
}
return Column(children: [
PasswdList(fetchedEntriesInApp),
RaisedButton(
onPressed: () {
Navigator.pushNamed(
context,
'/addPasswd',
arguments: AddPasswd(fetchEntries),
);
},
child: Text('Add Psswd'),
),
]);
});
}
}
PasswdList Widget
class PasswdList extends StatefulWidget {
var abc;
PasswdList(this.abc);
#override
State<PasswdList> createState() => _PasswdListState();
}
class _PasswdListState extends State<PasswdList> {
var fetchedEntriesInApp;
#override
Widget build(BuildContext context) {
var entries;
setState(() {
entries = widget.abc;
});
print(entries);
return Container(
height: 500,
child: ListView(
children: [
PasswdCard(),
],
),
);
}
}
You can add one variable for password list in your password list widget like,
class PasswdList extends StatefulWidget {
var passwordlist;
PasswdList(this.passwordlist);
#override
State<PasswdList> createState() => _PasswdListState();
}
class _PasswdListState extends State<PasswdList> {
var fetchedEntriesInApp;
#override
Widget build(BuildContext context) {
var entries;
setState(() {
entries = widget.passwordlist;
});
print(entries);
return Container(
height: 500,
child: ListView(
children: [
PasswdCard(),
],
),
);
}
}
And you can pass it to the navigator like,
RaisedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>PasswdList (fetchedEntriesInApp.values,
),
);
},
Since your PasswdList is a Stateful widget and it is embedded in your view, you can use the callback
#override
void didUpdateWidget(covariant PasswdList oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.abc != oldWidget.abc)
setState(() {
//You can have a var in your state class and re-assign it to the new value
});
}
Note: in order for this to work, you need to re-initialize the abc list and pass it to your widget, otherwise you might need to change the if statement condition

Cannot load image with flutter image_editor_pro

I want to use this package. But I seem to be missing something. This is my code:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return HomePage().xMaterialApp();
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File _image = File("assets/images/butterfly.jpg");
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _image == null,
isTue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse: Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
Widget condition({bool condtion, Widget isTue, Widget isFalse}) {
return condtion ? isTue : isFalse;
}
error: Cannot open file, path = 'assets/images/butterfly.jpg' (OS Error: No such file or directory, errno = 2).
How am I supposed to load an image with this?
I even tried to use Image from the get go. But no result. Maybe I am doing the File to Image conversion wrong?
**Update 1: **
class _HomePageState extends State<HomePage> {
final image = Image.asset('assets/images/butterfly.jpg');
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
image = geteditimage; // shows error asking to make the field not final
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: image == null,
isTue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse: Image.file(image).toCenter()) //The argument type 'Image' can't be assigned to the parameter type 'File'.
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
You need to add your asset directories to your pubspec.yaml.
For example:
dependencies:
...
dev_dependencies:
...
flutter:
uses-material-design: true
assets:
- assets/
- assets/images/
Then you can read the file as an image like so:
final image = Image.asset('assets/images/butterfly.jpg');
If you need to read the image as a file for the package you are trying to use, instead of coding in images, use a package like image_picker.
For your case:
class _HomePageState extends State<HomePage> {
File _image;
final picker = ImagePicker();
Future<void> getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _image == null,
isTue: 'Open Editor'.text().xRaisedButton(
onPressed: () async {
await getImage();
await getimageditor();
},
).toCenter(),
isFalse: Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
Widget condition({bool condtion, Widget isTue, Widget isFalse}) {
return condtion ? isTue : isFalse;
}
Solution for this is error is to prevent the Image.file to read from null by setting a null check:
_image == null ? Container() : Image.file(_image).toCenter())
The app will build without error, and after that you can use the image editor pro to edit your image.
If anyone wants to pass image to editor page from image picker :
make changes to image_editor_pro.dart file
final Color appBarColor;
final Color bottomBarColor;
final Directory pathSave;
final double pixelRatio;
final File image;
ImageEditorPro(
{this.appBarColor,
this.bottomBarColor,
this.pathSave,
this.pixelRatio,
this.image});
#override
void initState() {
timers();
_controller.clear();
type.clear();
// fontsize.clear();
offsets.clear();
// multiwidget.clear();
howmuchwidgetis = 0;
_image = widget.image;
super.initState();
}
**Then use this code **
import 'package:flutter/material.dart';
import 'dart:io';
// ignore: import_of_legacy_library_into_null_safe
import 'package:image_editor_pro/image_editor_pro.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:firexcode/firexcode.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:image_picker/image_picker.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return HomePage().xMaterialApp();
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File? _image;
final picker = ImagePicker();
Future<void> getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
// ignore: unnecessary_null_comparison
if (pickedFile != null) {
_image = File(pickedFile.path);
print("images : $_image");
} else {
print('No image selected.');
}
});
}
Future<void> getimageditor() async {
// ignore: unused_local_variable
final geteditimage =
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
image: _image,
);
})).then((geteditimage) {
print("image : $geteditimage");
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
}
#override
Widget build(BuildContext context) {
return condition(
// ignore: unnecessary_null_comparison
condtion: _image == null,
isTrue: 'Open Editor'.text().xRaisedButton(
onPressed: () async {
await getImage();
await getimageditor();
},
).toCenter(),
isFalse:
// ignore: unnecessary_null_comparison
_image == null ? Container() : Image.file(_image!).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTabText().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red))
.xRaisedButton(onPressed: () {
getimageditor();
});
}
}
Widget? condition({required bool condtion, Widget? isTrue, Widget? isFalse}) {
return condtion ? isTrue : isFalse;
}