Image_Picker Flutter, no image appears during compilation - flutter

here I have a problem when using Image_Picker under Flutter, my code looks good to me but I receive an error.
Indeed, no selected image appears during the execution of my code
Can you help me I join you my two classes for more understanding
Thank you
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class PageDescription extends StatefulWidget {
final String identite;
final String surnom;
final String caracteristiques;
final String role;
PageDescription(this.identite, this.surnom, this.caracteristiques, this.role);
#override
_PageDescriptionState createState() => _PageDescriptionState();
}
class _PageDescriptionState extends State<PageDescription> {
ImagePicker _imageFile = ImagePicker();
File? _image;
Future getImage(ImageSource source) async {
final pickFile = await _imageFile.getImage(source: source);
setState(() {
if (pickFile != null) {
_image = File(pickFile.path);
} else {
print("Pas d'image selectionnée");
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.identite),
actions: [
IconButton(
onPressed: () => getImage(ImageSource.gallery),
icon: Icon(Icons.photo_camera))
],
backgroundColor: Colors.teal,
),
body: SingleChildScrollView(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_image == null
? Text("Pas d'image selectionnée $_image")
: Image.file(_image!),
SizedBox(height: 20),
Text("Identite: ${widget.identite}", textScaleFactor: 1.5),
SizedBox(height: 20),
Text("Surnom: ${widget.surnom}", textScaleFactor: 1.5),
SizedBox(height: 20),
Text("Caracteristiques: ${widget.caracteristiques}",
textScaleFactor: 1.5),
SizedBox(height: 20),
Text("Rôle: ${widget.role}", textScaleFactor: 1.5)
],
)),
);
}
}
Error message in my debugging console:
Reloaded 0 libraries in 308ms.
[VERBOSE-2:ui_dart_state.cc(199)] Unhandled Exception: PlatformException(multiple_request, Cancelled by a second request, null, null)
#0 StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:597
#1 MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:158
<asynchronous suspension>
#2 MethodChannelImagePicker.pickImage
package:image_picker_platform_interface/…/method_channel/method_channel_image_picker.dart:29
<asynchronous suspension>
#3 _PageDescriptionState.getImage
package:ampc_93/page_description.dart:22
<asynchronous suspension>
Thank you in advance for your answers

Try this
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class PageDescription extends StatefulWidget {
final String identite;
final String surnom;
final String caracteristiques;
final String role;
PageDescription(this.identite, this.surnom, this.caracteristiques, this.role);
#override
_PageDescriptionState createState() => _PageDescriptionState();
}
class _PageDescriptionState extends State<PageDescription> {
File file;
Future getImage(ImageSource source) async {
File file = await ImagePicker.pickImage(source: source);
setState(() {
this.file = file;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.identite),
actions: [
IconButton(
onPressed: () => getImage(ImageSource.gallery),
icon: Icon(Icons.photo_camera))
],
backgroundColor: Colors.teal,
),
body: SingleChildScrollView(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_image == null
? Text("Pas d'image selectionnée $_image")
: Image.file(_image!),
SizedBox(height: 20),
Text("Identite: ${widget.identite}", textScaleFactor: 1.5),
SizedBox(height: 20),
Text("Surnom: ${widget.surnom}", textScaleFactor: 1.5),
SizedBox(height: 20),
Text("Caracteristiques: ${widget.caracteristiques}",
textScaleFactor: 1.5),
SizedBox(height: 20),
Text("Rôle: ${widget.role}", textScaleFactor: 1.5)
],
)),
);
}
}

Related

Unhandled Exception: FormatException: Unexpected end of input (at character 1) in flutter (in shared_preferences)

I'm making a task book, on a flutter, in this project I will use a lot of packages that I have not worked with before (this is not my first question on this project). My goal is to create tasks to add to the status (finished, not finished), and save them locally on the device. I wrote code (with some packages to help me figure it out) that does it all. But the problem arose when downloading questions from the local repository when starting the application. I have an error not to decode the data (in the repository I save a list of our tasks and status). Maybe someone faced such a problem I will be grateful for your help)
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:testjob/jsonTodo.dart';
void main() {
runApp(MaterialApp(
home: App(),
));
}
class _strikeThrough extends StatelessWidget {
final String todoText;
final bool todoCheck;
_strikeThrough(this.todoText, this.todoCheck) : super();
Widget _widget() {
if (todoCheck) {
return Text(
todoText,
style: TextStyle(
fontSize: 22.0,
),
);
} else {
return Text(
todoText,
style: TextStyle(fontSize: 22.0),
);
}
}
#override
Widget build(BuildContext context) {
return _widget();
}
}
class App extends StatefulWidget {
#override
AppState createState() {
return AppState();
}
}
final ValueNotifier<ThemeMode> _notifier = ValueNotifier(ThemeMode.light);
class AppState extends State<App> {
bool valText = true;
var IconsType = Icons.wb_sunny;
late Color ColorType = Colors.black;
var textController = TextEditingController();
var popUpTextController = TextEditingController();
List<TodoInfo> WidgetList = [];
#override
void dispose() {
textController.dispose();
popUpTextController.dispose();
super.dispose();
}
#override
void initState() {
getSP();
super.initState();
}
Future<void> addToSP(List<List<TodoInfo>> tList) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString('todoLists', jsonEncode(tList));
}
void getSP() async {
final prefs = await SharedPreferences.getInstance();
final List<dynamic> jsonData =
jsonDecode(prefs.getString('todoLists') ?? '');
if (jsonData.isNotEmpty) {
for (var data in jsonData) {
final d = TodoInfo.fromJson(data);
WidgetList.add(d);
}
setState(() {});
}
}
#override
Widget build(BuildContext context) {
return ValueListenableBuilder<ThemeMode>(
valueListenable: _notifier,
builder: (_, mode, __) {
return MaterialApp(
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: mode, // Decides which theme to show, light or dark.
home: Scaffold(
appBar: AppBar(
title: Text("Список задач"),
actions: <Widget>[
IconButton(
icon: Icon(IconsType, color: ColorType),
onPressed: () => {
if (_notifier.value == ThemeMode.light)
{
_notifier.value = ThemeMode.dark,
IconsType = Icons.dark_mode,
ColorType = Colors.white,
}
else
{
_notifier.value = ThemeMode.light,
IconsType = Icons.wb_sunny,
ColorType = Colors.black,
}
})
],
//backgroundColor: Colors.orange[500],
iconTheme: IconThemeData(color: Colors.white),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
"Tasks",
style: TextStyle(
fontSize: 70.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
IconButton(
color: Colors.black,
iconSize: 70,
constraints: const BoxConstraints(),
padding: EdgeInsets.fromLTRB(30.0, 10.0, 30, 10.0),
icon: const Icon(Icons.add_outlined),
onPressed: () {
if (textController.text
.replaceAll(" ", "")
.isNotEmpty) {
WidgetList.insert(0, TodoInfo(todoText:textController.text.replaceAll(" ", ""), todoCheck: false ));
addToSP;
setState(() {
valText = true;
textController.clear();
});
} else {
setState(() {
valText = false;
});
}
},
)
],
),
),
Container(
width: MediaQuery.of(context).size.height * 0.45,
child: TextField(
style: TextStyle(
fontSize: 22.0,
//color: Theme.of(context).accentColor,
),
controller: textController,
cursorWidth: 5.0,
autocorrect: true,
autofocus: true,
//onSubmitted: ,
),
),
Align(
child: (valText == false)
? Align(
child: Text(("Задача пустая"),
style: TextStyle(
fontSize: 25.0, color: Colors.red)),
alignment: Alignment.center)
: Align(
child: Text(
(""),
),
alignment: Alignment.center)),
Expanded(
child: ReorderableListView(
children: <Widget>[
for (final widget in WidgetList)
GestureDetector(
key: Key(widget.todoText),
child: Dismissible(
key: Key(widget.todoText),
child: CheckboxListTile(
controlAffinity:
ListTileControlAffinity.leading,
//key: ValueKey("Checkboxtile $widget"),
value: widget.todoCheck,
title: _strikeThrough(
widget.todoText, widget.todoCheck),
onChanged: (checkValue) {
//_strikethrough toggle
setState(() {
if (!checkValue!) {
widget.todoCheck = false;
} else {
widget.todoCheck = true;
}
});
},
),
background: Container(
child: Icon(Icons.delete),
alignment: Alignment.centerRight,
color: Colors.redAccent,
),
direction: DismissDirection.endToStart,
movementDuration:
const Duration(milliseconds: 200),
onDismissed: (dismissDirection) {
//Delete Todo
WidgetList.remove(widget);
},
),
)
],
onReorder: (oldIndex, newIndex) {
setState(() {
if (newIndex > oldIndex) {
newIndex -= 1;
}
var replaceWiget = WidgetList.removeAt(oldIndex);
WidgetList.insert(newIndex, replaceWiget);
});
},
),
)
],
),
));
});
}
}
class TodoInfo {
String todoText;
bool todoCheck;
TodoInfo({
required this.todoText,
required this.todoCheck,
});
factory TodoInfo.fromJson(Map<String, dynamic> json) {
return TodoInfo(todoText: json["todoText"], todoCheck: json["todoCheck"]);
}
factory TodoInfo.fromMap(Map<String, dynamic> map) =>
TodoInfo(
todoText: map["todoText"] ?? '',
todoCheck: map["todoCheck"] ?? '',
);
Map<String, dynamic> toJson() {
return {"todoText": todoText, "todoCheck": todoCheck};
}
#override
String toString() => '{todoText: $todoText, todoCheck: $todoCheck}';
}
My erorr
E/flutter (30831): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FormatException: Unexpected end of input (at character 1)
E/flutter (30831):
E/flutter (30831): ^
E/flutter (30831):
E/flutter (30831): #0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1404:5)
E/flutter (30831): #1 _ChunkedJsonParser.close (dart:convert-patch/convert_patch.dart:522:7)
E/flutter (30831): #2 _parseJson (dart:convert-patch/convert_patch.dart:41:10)
E/flutter (30831): #3 JsonDecoder.convert (dart:convert/json.dart:506:36)
E/flutter (30831): #4 JsonCodec.decode (dart:convert/json.dart:157:41)
E/flutter (30831): #5 jsonDecode (dart:convert/json.dart:96:10)
E/flutter (30831): #6 AppState.getSP (package:testjob/main.dart:85:5)
E/flutter (30831): <asynchronous suspension>
E/flutter (30831):
Change null check value from '' to '[]'.
You set jsonData with type List. In case prefs.getString('todoLists') is null, jsonDecode will take '' as parameter, but '' is not a valid json and cause the FormatException.
// final List<dynamic> jsonData = jsonDecode(prefs.getString('todoLists') ?? '');
-> final List<dynamic> jsonData = jsonDecode(prefs.getString('todoLists') ?? '[]');
Example: decode strings.
Updated: copy code in the file and paster to dartpad. since I don't have much time, I have omitted the things that are not so important, please add it after the main thread is up and running normally to run. check the dartpad console, you can see everytime you make an update to data, writeTodos was called, place your code in there (dartpad cant use sharedPref library)
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: App()));
class App extends StatefulWidget {
#override
AppState createState() => AppState();
}
class AppState extends State<App> {
final textController = TextEditingController();
final formKey = GlobalKey<FormState>();
List<TodoInfo> data = [];
#override
void initState() {
readTodos();
super.initState();
}
#override
void dispose() {
textController.dispose();
super.dispose();
}
void submitAddTodo() {
if (formKey.currentState?.validate() ?? false) {
final todoString = textController.text;
if (todoString.isNotEmpty) {
var todo = TodoInfo(todoText: todoString.trim(), todoCheck: false);
addTodo(todo);
textController.clear();
}
}
}
void removeTodoAt(int index) {
setState(() {
data = [...data]..removeAt(index);
writeTodos();
});
}
void updateTodoAt(int index, TodoInfo todo) {
setState(() {
data[index] = todo;
writeTodos();
});
}
void addTodo(TodoInfo todo) {
setState(() {
data = [todo, ...data];
writeTodos();
});
}
Future<void> writeTodos() async {
// write data to shared
print('writeTodos');
}
void readTodos() async {
print('readTodos');
// read data from your shared insteads hard code `prefsData`
final prefsData = [
TodoInfo(todoText: 'todo 1', todoCheck: false),
TodoInfo(todoText: 'todo 2', todoCheck: false),
];
setState(() => data = prefsData);
}
#override
Widget build(BuildContext context) {
return Scaffold(
//...
body: Form(
key: formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
"Tasks",
style: TextStyle(
fontSize: 70.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
IconButton(
color: Colors.black,
iconSize: 70,
constraints: const BoxConstraints(),
padding: EdgeInsets.fromLTRB(30.0, 10.0, 30, 10.0),
icon: const Icon(Icons.add_outlined),
onPressed: submitAddTodo,
)
],
),
),
Container(
width: MediaQuery.of(context).size.height * 0.45,
child: TextFormField(
style: TextStyle(fontSize: 22.0),
controller: textController,
autofocus: true,
validator: (value) {
if (value == null || value.isEmpty) return 'Список задач';
},
),
),
Expanded(child: _rTodos())
],
),
),
);
}
Widget _rTodos() {
var wgs = <Widget>[];
for (int i = 0; i < data.length; i++) {
var todo = data[i];
wgs.add(GestureDetector(
child: CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
value: todo.todoCheck,
title: Text(todo.todoText, style: TextStyle(fontSize: 22.0)),
onChanged: (checkValue) =>
updateTodoAt(i, todo..todoCheck = checkValue ?? false),
),
));
}
return ListView(
children: wgs
);
}
}
class TodoInfo {
String todoText;
bool todoCheck;
TodoInfo({required this.todoText, required this.todoCheck});
}

Unexpected null value when try to open drawer in flutter

I am trying to open the drawer and it gives me the below error:
======== Exception caught by gesture ===============================================================
The following TypeErrorImpl was thrown while handling a gesture:
Unexpected null value.
When the exception was thrown, this was the stack:
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 236:49 throw_
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 518:63 nullCheck
packages/l7/screens/main/view_model/main_view_model.dart 15:36 openOrCloseDrawer
packages/l7/screens/main/view/components/header.dart 35:42 <fn>
packages/flutter/src/material/ink_well.dart 989:21 [_handleTap]
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#ae119
debugOwner: GestureDetector
state: possible
won arena
finalPosition: Offset(35.8, 49.7)
finalLocalPosition: Offset(15.8, 12.9)
button: 1
sent tap down
====================================================================================================
and the below method is openOrCloseDrawer():
void openOrCloseDrawer() {
if (_scaffoldKey.currentState!.isDrawerOpen) {
_scaffoldKey.currentState!.openEndDrawer();
setState(ViewState.Idle);
} else {
_scaffoldKey.currentState!.openDrawer();
setState(ViewState.Idle);
}
}
related to the below ViewModel:
import 'package:flutter/material.dart';
import 'package:l7/enums/ScreenState.dart';
import 'package:l7/screens/BaseViewModel.dart';
class MainViewModel extends BaseViewModel {
int _selectedIndex = 0;
GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
int get selectedIndex => _selectedIndex;
List<String> get menuItems =>
["Cases", "Services", "About Us", "Careers", "Blog", "Contact"];
GlobalKey<ScaffoldState> get scaffoldkey => _scaffoldKey;
void openOrCloseDrawer() {
if (_scaffoldKey.currentState!.isDrawerOpen) {
_scaffoldKey.currentState!.openEndDrawer();
setState(ViewState.Idle);
} else {
_scaffoldKey.currentState!.openDrawer();
setState(ViewState.Idle);
}
}
void setMenuIndex(int index) {
_selectedIndex = index;
setState(ViewState.Idle);
}
}
and this is the below BaseViewModel:
import 'package:flutter/widgets.dart';
import 'package:l7/enums/ScreenState.dart';
import 'package:l7/utils/context_extentions.dart';
class BaseViewModel extends ChangeNotifier {
ViewState _state = ViewState.Idle;
ViewState get state => _state;
SwitchState _switchState = SwitchState.CLOSE;
SwitchState get switchState => _switchState;
void setState(ViewState viewState) {
_state = viewState;
notifyListeners();
}
void switchLanguage(bool state, BuildContext context) async {
state == true
? _switchState = SwitchState.OPEN
: _switchState = SwitchState.CLOSE;
notifyListeners();
if (context.locale == const Locale('ar', 'EG')) {
context.setLocale(const Locale('en', 'US'));
} else {
context.setLocale(const Locale('ar', 'EG'));
}
}
}
and this is the below Drawer component:
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:l7/screens/BaseScreen.dart';
import 'package:l7/screens/main/view_model/main_view_model.dart';
import 'package:l7/utils/constants.dart';
class SideMenu extends StatelessWidget {
// final MenuController _controller = Get.put(MenuController());
#override
Widget build(BuildContext context) {
return BaseScreen<MainViewModel>(
onModelReady: (mainViewModel){},
builder: (context, viewModel, _){
return Drawer(
child: Container(
color: kDarkBlackColor,
child: ListView(
children: [
DrawerHeader(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: kDefaultPadding * 3.5),
child: SvgPicture.asset("assets/icons/logo.svg"),
),
),
...List.generate(
viewModel.menuItems.length,
(index) => DrawerItem(
isActive: index == viewModel.selectedIndex,
title: viewModel.menuItems[index],
press: () {
viewModel.setMenuIndex(index);
},
),
),
],
),
),
);
},
);
}
}
class DrawerItem extends StatelessWidget {
final String? title;
final bool? isActive;
final VoidCallback? press;
const DrawerItem({
Key? key,
#required this.title,
#required this.isActive,
#required this.press,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return SafeArea(
child: ListTile(
contentPadding: EdgeInsets.symmetric(horizontal: kDefaultPadding),
selected: isActive!,
selectedTileColor: kPrimaryColor,
onTap: press,
title: Text(
title!,
style: TextStyle(color: Colors.white),
),
),
);
}
}
and this is the Header Widget which contains the drawer:
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:l7/screens/BaseScreen.dart';
import 'package:l7/screens/main/view/components/web_menu.dart';
import 'package:l7/screens/main/view_model/main_view_model.dart';
import 'package:l7/services/responsive.dart';
import 'package:l7/utils/constants.dart';
import 'package:l7/utils/texts.dart';
import 'header_right_side.dart';
class Header extends StatelessWidget {
#override
Widget build(BuildContext context) {
return BaseScreen<MainViewModel>(
onModelReady: (mainViewModel) {},
builder: (context, viewModel, _) {
return SafeArea(
child: Column(
children: [
Column(
children: [
Row(
children: [
if (!Responsive.isDesktop(context))
IconButton(
icon: Icon(
Icons.menu,
color: kBlackBlue,
),
onPressed: () {
viewModel.openOrCloseDrawer();
},
),
Image.asset("assets/images/l7_image.png", height: MediaQuery.of(context).size.height * 0.15,),
Spacer(),
if (Responsive.isDesktop(context)) WebMenu(),
Spacer(),
HeaderRightSide(),
],
),
// SizedBox(height: kDefaultPadding * 2),
Container(
width: double.infinity,
height: MediaQuery.of(context).size.height * 0.27,
decoration: BoxDecoration(
image: DecorationImage(image: AssetImage('assets/images/blog_bg.png'), fit: BoxFit.cover)
),
child: Row(
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
headLine30TitleText(
tr("Welcome to Our Blog"),
context,
),
Padding(
padding:
const EdgeInsets.symmetric(vertical: kDefaultPadding),
child: Text(
"Stay updated with the newest design and development stories, case studies, \nand insights shared by DesignDK Team.",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontFamily: 'Raleway',
height: 1.5,
),
),
),
FittedBox(
child: TextButton(
onPressed: () {},
child: Row(
children: [
Text(
"Learn More",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
SizedBox(width: kDefaultPadding / 2),
Icon(
Icons.arrow_forward,
color: Colors.white,
),
],
),
),
),
],
),
),
IconButton(onPressed: (){}, icon: Icon(Icons.keyboard_arrow_right, color: Colors.white,))
],
),
),
if (Responsive.isDesktop(context))
SizedBox(height: kDefaultPadding),
],
)
],
),
);
},
);
}
}
I hope someone could help, and let me know if there's any missing details or code. :)
The solution in the below line code in Header widget:
instead of:
viewModel.openOrCloseDrawer();
add this line:
Scaffold.of(context).openDrawer();

i can't get all the data from an api

i want to display some data that i receive from a web Api in the form of posts, most of that data gets displayed on the screen normally but all of a sudden an error arises and all the remaining posts become red.
the error i get:
The following NoSuchMethodError was thrown building:
The method '[]' was called on null.
Receiver: null
Tried calling: [](0)
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _NewsScreenState.build.<anonymous closure>.<anonymous closure>
#2 SliverChildBuilderDelegate.build
package:flutter/…/widgets/sliver.dart:449
#3 SliverMultiBoxAdaptorElement._build
package:flutter/…/widgets/sliver.dart:1130
#4 SliverMultiBoxAdaptorElement.performRebuild.processElement
package:flutter/…/widgets/sliver.dart:1076
the way how i display the posts:
import 'package:flutter/material.dart';
class NewsFrame extends StatelessWidget {
final String title;
final String excerpt;
final String webUrl;
final String imageUrl;
final String publishedDateTime;
final String sourceName;
const NewsFrame(
{this.title,
this.excerpt,
this.webUrl,
this.imageUrl,
this.publishedDateTime,
this.sourceName});
String formatTime(String receivedDate) {
String date = receivedDate.substring(0, 11);
return "${date.substring(0, 4)}/${date.substring(5, 7)}/${date.substring(8, date.length-1)}";
}
void delayedMomemt() async {
await Future.delayed(Duration(milliseconds: 200));
print(this.title);
print(this.excerpt);
print(this.webUrl);
print(this.publishedDateTime);
print(this.imageUrl);
print(this.sourceName);
}
#override
Widget build(BuildContext context) {
this.delayedMomemt();
return Container(
decoration: BoxDecoration(color: Colors.green),
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(this.title),
this.imageUrl == null
? SizedBox(height: 0)
: Image.network(this.imageUrl),
Text(this.excerpt),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(this.publishedDateTime == null
? "No Date"
: this.formatTime(this.publishedDateTime)),
Text(this.sourceName ?? "Unknown")
],
)
],
),
);
}
}
how i send the data to the posts file:
class NewsScreen extends StatefulWidget {
#override
_NewsScreenState createState() => _NewsScreenState();
}
class _NewsScreenState extends State<NewsScreen> {
var articalsData;
#override
void initState() {
super.initState();
GetData getData = GetData();
this.articalsData = getData.getArticals();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: ThmColors.lightBlueClr,
body: Stack(
children: [
FadedBg(img: "img21"),
Center(
child: FutureBuilder(
future: this.articalsData,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: [
SizedBox(height: MediaQuery.of(context).size.height / 6),
Expanded(
child: ListView.builder(
itemCount: snapshot.data['news'].length,
itemBuilder: (context, index) => NewsFrame(
title: snapshot.data['news'][index]['title'],
excerpt: snapshot.data['news'][index]['excerpt'],
webUrl: snapshot.data['news'][index]['webUrl'],
imageUrl: snapshot.data['news'][index]['images'][0]['url'],
publishedDateTime: snapshot.data['news'][index]['publishedDateTime'],
sourceName: snapshot.data['news'][index]['provider']['name'],
),
),
),
],
);
} else if (snapshot.hasError) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Oops! something went wrong.',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
)),
Text('(Check out your: Signal, Internet, WiFi...)',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w500,
letterSpacing: -0.5)),
],
);
}
return LoadingRing();
},
),
),
Positioned(
top: 0,
child: UpperBar(titleTxt: "News"),
),
],
),
);
}
}
PLEASE HELP!
It looks like not every article has an images array, try checking if its null before getting the first image, if it is provide some sort of default image instead. Something like this:
imageUrl: getImage(snapshot.data['news'][index])
...
String getImage(data){
if (data['images'] == null || data['images'].isEmpty)
return 'default_image_url'
return data['images'][0]['url']
}

Uploading and displaying an image from Computer in to a FLUTTER WEB APP during runtime

I am trying to upload an image via a FLUTTER WEB app from my computer internal folder (macos) and truing to display the same image in the same FLUTTER WEB app. Both uploading and displaying is done during run time of the app.
I am getting the following exception. How do I fix this issue?
Thank you.
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
Expected a value of type 'Widget?', but got one of type 'DecorationImage'
main.dart
import 'dart:convert';
import 'dart:html';
import 'dart:typed_data';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: ImageUploader(),
);
}
}
class ImageUploader extends StatefulWidget {
#override
_ImageUploaderState createState() => _ImageUploaderState();
}
class _ImageUploaderState extends State<ImageUploader> {
Uint8List imagevalue;
#override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
return Scaffold(
body: Container(
width: width,
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(vertical: 18.0),
child: Text(
'Mah Links',
style: TextStyle(
fontFamily: 'Karla',
fontSize: 20,
fontWeight: FontWeight.w800,
),
),
),
Container(
child: imagevalue == null
? Text('No Image')
: DecorationImage(
fit: BoxFit.cover,
image: Image.memory(imagevalue).image)),
],
),
),
floatingActionButton: FloatingActionButton.extended(
heroTag: 'picker',
elevation: 0,
backgroundColor: Colors.tealAccent[400],
hoverElevation: 0,
label: Row(
children: <Widget>[
Icon(Icons.file_upload),
SizedBox(width: 10),
Text('Upload Image')
],
),
onPressed: () => uploadImage(),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
);
}
uploadImage() {
// HTML input element
InputElement uploadInput = FileUploadInputElement();
uploadInput.click();
uploadInput.onChange.listen(
(changeEvent) {
final file = uploadInput.files.first;
final reader = FileReader();
// The FileReader object lets web applications asynchronously read the
// contents of files (or raw data buffers) stored on the user's computer,
// using File or Blob objects to specify the file or data to read.
// Source: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
reader.readAsDataUrl(file);
String imgString = reader.result; //.toString();
Uint8List base64string = Base64Decoder().convert(imgString);
reader.onLoadEnd.listen(
(loadEndEvent) async {
setState(() {
imagevalue = base64string;
});
},
);
},
);
}
}
For anyone looking for a solution to pick an image from the computer internal directory from a flutter web app during runtime:
make sure to insert the file_picker package into pubspec.yaml
import 'dart:html';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: ImageUploader(),
);
}
}
class ImageUploader extends StatefulWidget {
#override
_ImageUploaderState createState() => _ImageUploaderState();
}
class _ImageUploaderState extends State<ImageUploader> {
Uint8List imagevalue;
#override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
return Scaffold(
body: Container(
width: width,
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(vertical: 18.0),
child: Text(
'Mah Links',
style: TextStyle(
fontFamily: 'Karla',
fontSize: 20,
fontWeight: FontWeight.w800,
),
),
),
Container(
child: imagevalue == null
? Text('No Image')
: Image.memory(imagevalue))
// : DecorationImage(
// fit: BoxFit.cover,
// image: Image.memory(imagevalue).image)),
],
),
),
floatingActionButton: FloatingActionButton.extended(
heroTag: 'picker',
elevation: 0,
backgroundColor: Colors.tealAccent[400],
hoverElevation: 0,
label: Row(
children: <Widget>[
Icon(Icons.file_upload),
SizedBox(width: 10),
Text('Upload Image')
],
),
onPressed: () => uploadImage(),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
);
}
uploadImage() async {
FilePickerResult result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['png', 'jpg', 'svg', 'jpeg']);
if (result != null) {
PlatformFile file = result.files.first;
setState(() {
imagevalue = file.bytes;
});
} else {
// User canceled the picker
}
}
}

Set data in the app, which is retrive from firebase

Image is not coming but all the data in the firebase database is showing in the app.
import 'package:flutter/material.dart';
import 'Authentication.dart';
import 'photoUpload.dart';
import 'Posts.dart';
import 'package:firebase_database/firebase_database.dart';
// import 'package:flutter_blogapp/Authentication.dart';
// import 'package:flutter_blogapp/photoUpload.dart';
class HomePage extends StatefulWidget
{
HomePage
(
{
this.auth,
this.onSignedOut,
}
);
final AuthImplementation auth;
final VoidCallback onSignedOut;
#override
State<StatefulWidget> createState()
{
return _HomePageState();
}
}
class _HomePageState extends State<HomePage>
{
List<Posts> postsList = [];
#override
void initState()
{
super.initState();
DatabaseReference postsRef = FirebaseDatabase.instance.reference().child("Posts");
postsRef.once().then((DataSnapshot snap)
{
var KEYS = snap.value.keys;
var DATA = snap.value;
postsList.clear();
for(var individualKey in KEYS)
{
Posts posts = new Posts
(
DATA[individualKey]['image'],
DATA[individualKey]['description'],
DATA[individualKey]['data'],
DATA[individualKey]['time'],
);
postsList.add(posts);
}
setState(()
{
print('Length : $postsList.length');
});
});
}
void _logoutUser() async
{
try
{
await widget.auth.signOut();
widget.onSignedOut();
}
catch (e)
{
print(e.toString());
}
}
#override
Widget build(BuildContext context)
{
return new Scaffold
(
appBar: new AppBar
(
title: new Text('Home'),
),
body : new Container
(
child: postsList.length == 0 ? new Text(" No Post available ") : new ListView.builder
(
itemCount: postsList.length,
itemBuilder: (_, index)
//itemBuilder: (BuildContext _, int index ) //<-----
{
return PostsUI(postsList[index].image, postsList[index].description, postsList[index].date, postsList[index].time);
}
),
),
bottomNavigationBar: new BottomAppBar
(
color: Colors.pink,
child: new Container
(
margin: const EdgeInsets.only(left: 70.0, right: 70.0),
child: new Row
(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: <Widget>
[
new IconButton
(
icon: new Icon(Icons.local_car_wash),
iconSize: 50,
color: Colors.white,
onPressed: _logoutUser,
),
new IconButton
(
icon: new Icon(Icons.add_a_photo),
iconSize: 50,
color: Colors.white,
onPressed: ()
{
Navigator.push
(
context,
MaterialPageRoute(builder: (context)
{
return new UploadPhotoPage();
})
);
},
),
],
),
),
),
);
}
// Designing Posts UI
Widget PostsUI(String image, String description, String date, String time)
{
return new Card
(
elevation: 10.0,
margin: EdgeInsets.all(15.0),
child: new Container
(
padding: new EdgeInsets.all(14.0),
child: new Column
(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>
[
new Row
(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>
[
new Text
(
date,
style: Theme.of(context).textTheme.subtitle,
textAlign: TextAlign.center,
),
new Text
(
time,
style: Theme.of(context).textTheme.subtitle,
textAlign: TextAlign.center,
), //<----
],
),
SizedBox(height: 10.0,),
new Image.network(image, fit:BoxFit.cover),
SizedBox(height: 10.0,),
new Text
(
description,
style: Theme.of(context).textTheme.subhead,
textAlign: TextAlign.center,
),
],
)
)
);
}
}
The following errors are showing:
═══════ Exception caught by image resource service
════════════════════════════ The following ArgumentError was thrown
resolving an image codec: Invalid argument(s): No host specified in
URI file:///image
When the exception was thrown, this was the stack
0 _HttpClient._openUrl (dart:_http/http_impl.dart:2276:9)
1 _HttpClient.getUrl (dart:_http/http_impl.dart:2197:48)
2 NetworkImage._loadAsync package:flutter/…/painting/_network_image_io.dart:84
3 NetworkImage.load package:flutter/…/painting/_network_image_io.dart:47
4 ImageProvider.resolve...
package:flutter/…/painting/image_provider.dart:327 ... Image provider:
NetworkImage("image", scale: 1.0) Image key: NetworkImage("image",
scale: 1.0)
The main part of the error message is:
Invalid argument(s): No host specified in URI file:///image
From this it looks like you're storing a local file:/// reference into the database, instead of a globally accessible URL (typically starting with http:// or https://).
The solution is in the code that writes to the database, to actually upload the image to a public storage place (such as to Firebase Storage) and then write the resulting download URL into the database.