I'm trying to display a image on an android phone from the phones photo gallery using flutter and the /image_picker import but I keep on running into this problem:
'A value of type 'XFile?' can't be assigned to a variable of type 'File'.'
Is there anyway of converting an xfile to a file type?
here is the code coursing the problem
imageSelectorGallery() async {
galleryFile = await ImagePicker.pickImage(
source: ImageSource.gallery,
maxHeight: 50.0,
maxWidth: 50.0,
);
setState(() {});
}
here is the full code
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new GalleryAccess(),
debugShowCheckedModeBanner: false,
);
}
}
class GalleryAccess extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return new GalleryAccessState();
}
}
class GalleryAccessState extends State<GalleryAccess> {
late File galleryFile;
#override
Widget build(BuildContext context) {
//display image selected from gallery
imageSelectorGallery() async {
galleryFile = await ImagePicker.pickImage(
source: ImageSource.gallery,
maxHeight: 50.0,
maxWidth: 50.0,
);
setState(() {});
}
return new Scaffold(
appBar: new AppBar(
title: new Text('Gallery Access'),
backgroundColor: Colors.green,
actions: <Widget>[
Text("GFG",textScaleFactor: 3,)
],
),
body: new Builder(
builder: (BuildContext context) {
return Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new RaisedButton(
child: new Text('Select Image from Gallery'),
onPressed: imageSelectorGallery,
),
SizedBox(
height: 200.0,
width: 300.0,
child: galleryFile == null
? Center(child: new Text('Sorry nothing selected!!'))
: Center(child: new Image.file(galleryFile)),
)
],
),
);
},
),
);
}
}
First of all you have to take galleryFile as XFile type and wherever you want to use that picked Xfile then use like below code.
SizedBox(
height: 200.0,
width: 300.0,
child: galleryFile == null
? Center(child: new Text('Sorry nothing selected!!'))
: Center(child: new Image.file(File(galleryFile.path))))
Related
I'm new to flutter and making my first webview app. Here I'm trying to add a spinner every time when a user tries to click the link or page load. I want to make spinner background opacity a bit low just like the given example, but opacity doesn't work at all.
My approach
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
color: Colors.white.withOpacity(0.5),
child: Center(
child: SpinKitDualRing(
color: Colors.pinkAccent,
size: 45.0,
controller: AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1200),
),
),
),
)
I'm using here flutter_spinkit package as a spinner.
Full code
// ignore_for_file: prefer_const_constructors
// ignore: use_key_in_widget_constructors
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:splash_screen_view/SplashScreenView.dart';
void main(){
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Color(0xff1e2229)
));
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
Widget spalshfirst = SplashScreenView(
navigateRoute: WebViewClass(),
duration: 3000,
imageSize: 80,
imageSrc: 'assets/splash.png',
text: "Food Delivery",
textType: TextType.TyperAnimatedText,
textStyle: TextStyle(
fontSize: 25.0,
),
colors: const [
Colors.purple,
Colors.blue,
Colors.yellow,
Colors.red,
],
backgroundColor: Colors.white,
);
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: spalshfirst
)
);
}
}
class WebViewClass extends StatefulWidget {
WebViewState createState() => WebViewState();
}
class WebViewState extends State<WebViewClass> with TickerProviderStateMixin{
late WebViewController _controller;
final Completer<WebViewController> _controllerCompleter =
Completer<WebViewController>();
//Make sure this function return Future<bool> otherwise you will get an error
Future<bool> _onWillPop(BuildContext context) async {
if (await _controller.canGoBack()) {
_controller.goBack();
return Future.value(false);
} else {
return Future.value(true);
}
}
#override
void initState() {
super.initState();
// Enable hybrid composition.
if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
}
bool isLoading = false;
final key = UniqueKey();
int position = 0;
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () => _goBack(context),
child: Scaffold(
resizeToAvoidBottomInset: false,
appBar: null,
body: SafeArea(
child: IndexedStack(
index: position,
children: [
WebView(
initialUrl: 'https://google.com',
javascriptMode: JavascriptMode.unrestricted,
key: key,
onPageStarted: (value) {
setState(() {
position = 1;
});
},
onPageFinished: (value) {
setState(() {
position = 0;
});
},
onWebViewCreated: (WebViewController webViewController) {
_controllerCompleter.future
.then((value) => _controller = value);
_controllerCompleter.complete(webViewController);
},
),
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
color: Colors.white.withOpacity(0.5),
child: Center(
child: SpinKitDualRing(
color: Colors.pinkAccent,
size: 45.0,
controller: AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1200),
),
),
),
)
],
),
),
),
);
}
Future<bool> _goBack(BuildContext context) async {
if (await _controller.canGoBack()) {
_controller.goBack();
return Future.value(false);
} else {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Do you want to exit from Foodrive?'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('No'),
),
TextButton(
onPressed: () {
SystemNavigator.pop();
},
child: Text('Yes'),
),
],
));
return Future.value(true);
}
}
}
Since the container is containing only the spinner, and not the background widget, settings its opacity won't work,
I'd suggest using the Stack widget with the Opacity widget
Something like this (just a reference point):
return Stack(children: [
Opacity(opacity: 0.5, child: resetOfTheWidgetTree),
Container(child: spinWidgetHere),
]);
I am trying to create a music app. I managed to get all the songs list but I cannot seem to get album artwork from the song metadata. I am using flutter_audio_query: ^0.3.5+6 plugin for this.
I cannot get the artwork by using songs[index].albumArtwork. It always returns null instead of the image path. What is the problem with my code?
Here is my code
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_audio_query/flutter_audio_query.dart';
class HomePage extends StatefulWidget {
const HomePage({Key key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final FlutterAudioQuery audioQuery = FlutterAudioQuery();
List<SongInfo> songs = [];
#override
void initState() {
super.initState();
checkPermission();
getAllSongs();
}
Future<void> getAllSongs() async {
songs = await audioQuery.getSongs();
}
Future<void> checkPermission() async {
if (await Permission.storage.request().isGranted) {
setState(() {});
} else {
_showDialog();
}
}
void _showDialog() async {
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Warning'),
content: SingleChildScrollView(
child: ListBody(
children: const <Widget>[
Text('The app needs storage permission in order to work'),
],
),
),
actions: <Widget>[
TextButton(
child: const Text('OK'),
onPressed: () async {
Navigator.of(context).pop();
await checkPermission();
},
),
],
);
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFF3C3C3C),
appBar: AppBar(
elevation: 0.0,
centerTitle: true,
toolbarHeight: 64.0,
leading: Icon(
Icons.music_note_rounded,
),
actions: [
IconButton(
onPressed: () {},
icon: Icon(Icons.search_rounded),
),
],
backgroundColor: Colors.transparent,
title: Text(
"All Songs",
style: GoogleFonts.expletusSans(
fontWeight: FontWeight.bold,
),
),
),
body: ListView.builder(
itemCount: songs.length,
itemBuilder: (context, index) {
return ListTile(
leading: Image.asset(
songs[index].albumArtwork != null
? songs[index].albumArtwork
: "assets/placeholder.png",
),
title: Text(songs[index].title),
subtitle: Text(songs[index].artist),
);
},
),
);
}
}
Sometimes albumArtwork will return a null value. In this case you need to use [FlutterAudioQuery().getArtwork()].
Documentation
Use ResourceType.ALBUM to get album image and ResourceType.SONG to song image.
Example:
// check if artistArtPath isn't available.
(song.artwork == null)
? FutureBuilder<Uint8List>(
future: audioQuery.getArtwork(
type: ResourceType.SONG, id: song.id),
builder: (_, snapshot) {
if (snapshot.data == null)
return Container(
height: 250.0,
child: Center(
child: CircularProgressIndicator(),
),
);
return CardItemWidget(
height: 250.0,
title: artist.name,
// The image bytes
// You can use Image.memory widget constructor
// or MemoryImage image provider class to load image from bytes
// or a different approach.
rawImage: snapshot.data,
);
}) :
// or you can load image from File path if available.
Image.file( File( artist.artistArtPath ) )
How can I use Flutter to print in Sunmi V2?
I am trying to use this package: https://pub.dev/packages/sunmi
But there is no clear explanation of how to use it
There is a new flutter plugin for Sunmi printers: flutter_sunmi_printer
It can print texts with styles (bold, underline, align, font size), tables (using Bootstrap-like grid system), images etc.
import 'package:flutter_sunmi_printer/flutter_sunmi_printer.dart';
// Text with styles
SunmiPrinter.text('left');
SunmiPrinter.text(
'center',
styles: SunmiStyles(bold: true, underline: true, align: SunmiAlign.center),
);
SunmiPrinter.text(
'right',
styles: SunmiStyles(bold: true, underline: true, align: SunmiAlign.right),
);
// Table
SunmiPrinter.row(
cols: [
SunmiCol(text: 'col1', width: 4),
SunmiCol(text: 'col2', width: 4, align: SunmiAlign.center),
SunmiCol(text: 'col3', width: 4, align: SunmiAlign.right),
],
);
// Image
ByteData bytes = await rootBundle.load('assets/rabbit_black.jpg');
final buffer = bytes.buffer;
final imgData = base64.encode(Uint8List.view(buffer));
SunmiPrinter.image(imgData);
You can see github https://github.com/irpankusuma/SUNMI_AIDL_PRINTER
Full example code https://github.com/irpankusuma/SUNMI_AIDL_PRINTER/tree/master/example
In pubspec.yaml manually add
assets:
- assets/images/
from widget/config.dart add the following png and jpg to assets/images
const String defaultLogoImage = "assets/images/logo.png";
const String defaultPrintLogoImage = "assets/images/print-logo.png";
const String defaultErrorImage = "assets/images/error_404.jpg";
Print Page
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sunmi_aidl_print_example/blocs/blocs.dart';
import 'package:sunmi_aidl_print_example/blocs/printing_bloc.dart';
import 'package:sunmi_aidl_print_example/config.dart' as config;
import 'package:flutter/material.dart';
import 'package:sunmi_aidl_print/models.dart';
import 'package:sunmi_aidl_print/sunmi_aidl_print.dart';
import 'package:sunmi_aidl_print_example/models/models.dart';
import 'package:sunmi_aidl_print_example/common/common.dart';
class PrintingPage extends StatefulWidget {
#override
State<PrintingPage> createState() => PrintingPageState();
}
class PrintingPageState extends State<PrintingPage>{
List<SunmiPrinter> array = <SunmiPrinter>[];
List<MenuService> menus = <MenuService>[];
Uint8List bytes;
#override
void initState() {
super.initState();
_getBytesImage();
SunmiAidlPrint.bindPrinter();
}
#override
void dispose() {
super.dispose();
SunmiAidlPrint.unbindPrinter();
}
void _getBytesImage() async{
ByteData getBytes = await rootBundle.load(config.defaultPrintLogoImage);
Uint8List image = getBytes.buffer.asUint8List();
setState(() => bytes = image);
}
void _generateMenu() {
menus.add(new MenuService(
name:'TEXT',
icons: Icon(Icons.text_fields),
onTap: () => null
));
}
void _openAlert({ String error}){
showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Alert'),
content: new Text(error),
)
);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('PRINT EXAMPLE'),
),
body: new Container(
child: BlocListener<PrintingBloc,PrintingState>(
listener: (context,state){
if(state is ErrorPrinting){ _openAlert(error:state.error); }
},
child: BlocBuilder<PrintingBloc,PrintingState>(
builder: (context,state){
if(state is LoadingPrinting){ return new LoadingIndicator(); }
if(state is InitialPrinting){
return new Container(
child: new MenuServiceState(items:menus,),
);
}
if(state is LoadedPrinting){
return new Container(
child: new MenuServiceState(items:menus,),
);
}
new Container();
},
),
),
),
);
}
}
class MenuServiceState extends StatelessWidget {
final List<MenuService> items;
final int crossAxis;
MenuServiceState({ this.items, this.crossAxis=3 });
#override
Widget build(BuildContext context) {
return new Container(
margin: EdgeInsets.only(top:8.0,bottom:8.0),
child: new GridView.builder(
shrinkWrap: true,
gridDelegate:new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:crossAxis),
physics: ClampingScrollPhysics(),
itemCount: items.length,
itemBuilder: (context,i) => new GestureDetector(
onTap: () => items[i].onTap,
child: new Container(
alignment: Alignment.center,
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Container(
decoration: new BoxDecoration(
border: Border.all(color:Colors.grey,width:1.0),
borderRadius: new BorderRadius.all(new Radius.circular(20.0))
),
padding: EdgeInsets.all(12.0),
child: items[i].icons,
),
new Padding(padding: EdgeInsets.only(top:6.0),),new Text("${items[i].name}")
],
),
),
),
),
);
}
}
I'm using Flutter for first time for one of my projects which is a Newspaper App.
The problem takes place when I try to navigate from main.dart to newsfeed_for_other_category.dart using MaterialPageRoute from my Drawer. In that screen it shows the news but with a black background. But in the screen newsfeed_screen.dart which is called in the body in my main.dart it shows perfectly.
I'm posting the codes below.
main.dart
import 'package:flutter/material.dart';
import './SizeConfig.dart';
import './screens/newsfeed_screen.dart';
import 'package:curved_navigation_bar/curved_navigation_bar.dart';
import 'factory/widget_factory.dart';
import 'widgets/top_news_widget.dart';
import 'package:splashscreen/splashscreen.dart';
import './widgets/drawer.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Newspaper App',
theme: ThemeData(
primarySwatch: Colors.blue,
//backgroundColor: Colors.lightGreenAccent,
),
home: MyHomePage(title: 'The Business Standard'),
routes: <String, WidgetBuilder> {
'/screen1': (BuildContext context) => new NewsFeedScreen(216, 5, "Top News"),
'/screen2' : (BuildContext context) => new NewsFeedScreen(4, 7, "National"),
'/screen3' : (BuildContext context) => new NewsFeedScreen(13, 70, "International"),
/*'/screen4' : (BuildContext context) => new Screen4()*/
},
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>(debugLabel: '_MainScreenKey');
Widget build(BuildContext context) {
return SplashScreen(
seconds: 3,
navigateAfterSeconds: AfterSplash(),
title: Text(
'The Business Standard',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0
),
),
image: Image.asset(
'assets/TBS_logo.jpg',
),
backgroundColor: Colors.white,
styleTextUnderTheLoader: TextStyle(),
photoSize: 100.0,
onClick: ()=>print("Flutter Egypt"),
loaderColor: Colors.red
);
}
}
class AfterSplash extends StatefulWidget {
#override
_AfterSplashState createState() => _AfterSplashState();
}
class _AfterSplashState extends State<AfterSplash> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>(debugLabel: '_MainScreenKey');
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
backgroundColor: Colors.white,
title: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Image.asset(
'assets/TBS.png',
fit: BoxFit.cover,
height: 45,
)
],
),
leading: IconButton(
icon: Icon(Icons.dehaze),
color: Colors.black,
onPressed: () => _scaffoldKey.currentState.openDrawer(),
),
),
drawer: SideDrawer(),
body: NewsFeedScreen(22, 71, "Sports"),
bottomNavigationBar: CurvedNavigationBar(
backgroundColor: const Color(0xFF2b4849),
items: <Widget>[
Icon(Icons.bookmark, size: 30,),
Icon(Icons.perm_identity, size: 30,),
Icon(Icons.settings, size: 30,),
],
onTap: (index) {
if(index == 2) {
_scaffoldKey.currentState.showSnackBar(const SnackBar(
content: const Text('Will open Settings menu')));
} else if(index == 0) {
_scaffoldKey.currentState.showSnackBar(const SnackBar(
content: const Text('Implement Bookmark function')));
} else {
_scaffoldKey.currentState.showSnackBar(const SnackBar(
content: const Text('Will show User profile and information')));
}
},
),
);
}
}
newsfeed_for_other_category.dart, the page to which I'm navigating and this is where the black background shows up.
import 'package:flutter/material.dart';
import '../SizeConfig.dart';
import '../widgets/headlines.dart';
import '../widgets/secondary_headlines.dart';
import '../widgets/listed_news.dart';
import '../models/NewsPost.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:developer';
import '../screens/newsPost_details.dart';
import '../screens/newsfeed_for_specific_category.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import '../transition_animation_routes/ScaleTransitionRoute.dart';
import '../widgets/top_news_widget.dart';
class NewsfeedForOtherCategory extends StatefulWidget {
int categoryId;
int childrenCategoryId;
String categoryName;
NewsfeedForOtherCategory(this.categoryId, this.childrenCategoryId, this.categoryName);
#override
_NewsfeedForOtherCategoryState createState() => _NewsfeedForOtherCategoryState(this.categoryId, this.childrenCategoryId, this.categoryName);
}
class _NewsfeedForOtherCategoryState extends State<NewsfeedForOtherCategory> {
int categoryId;
int childrenCategoryId;
String categoryName;
_NewsfeedForOtherCategoryState(this.categoryId, this.childrenCategoryId, this.categoryName);
bool _isRequestSent = false;
List<NewsPost> newsPostList = [];
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
if(!_isRequestSent) {
_sendRequest();
}
return Container(
alignment: Alignment.center,
child: !_isRequestSent
? CircularProgressIndicator()
: Container(
child: ListView.builder(
itemCount: newsPostList.length,
scrollDirection: Axis.vertical,
itemBuilder: (BuildContext context, int index) {
return _getNewsPostWidgets(index);
}
),
),
);
}
void _sendRequest() async {
String url = "https://tbsnews.net/json/category/news/"+this.categoryId.toString()+"/"+this.childrenCategoryId.toString()+"";
http.Response response = await http.get(url);
List<dynamic> decode = json.decode(response.body);
log('response: $response');
List results = decode[0]['items'];
for (var jsonObject in results) {
var post = NewsPost.getNewsPostFromAPI(jsonObject);
newsPostList.add(post);
print(post);
}
setState(() => _isRequestSent = true);
}
Widget _getNewsPostWidgets(int index) {
var newsPost = newsPostList[index];
if(index < this.newsPostList.length) {
if(index == 0) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
ScaleTransitionRoute(
page: NewsPostDetails(newsPostList, index)
)
);
},
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
//constraints: BoxConstraints(minWidth: double.infinity, maxWidth: double.infinity),
constraints: BoxConstraints.expand(
width: double.infinity,
height: 40
),
color: const Color(0xFF2b4849),
child: Text(
this.categoryName,
style: TextStyle(
fontSize: 33,
color: Colors.white
),
),
),
BlockHeadline(newsPost)
],
)
);
}
else {
return GestureDetector(
onTap: () {
Navigator.push(
context,
ScaleTransitionRoute(
page: NewsPostDetails(newsPostList, index)
)
);
},
child: ListedNews(newsPost),
);
}
}
else {
return Container(
color: const Color(0xFF2b4849),
child: index == 3 ? FlatButton(
child: Text(
"Load More",
style: TextStyle(
color: Colors.white
),
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => NewsFeedForSpecificCategory(newsPostList)
)
);
},
) : Container(),
);
}
}
openNewsPostDetails(List<NewsPost> newsPostList, int index) {
Navigator.push(
context,
ScaleTransitionRoute(
page: NewsPostDetails(newsPostList, index)
)
);
}
}
drawer.dart
import 'package:flutter/material.dart';
import '../SizeConfig.dart';
import '../screens/newsfeed_for_other_category.dart';
class SideDrawer extends StatelessWidget {
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
return SizedBox(
width: SizeConfig.safeBlockHorizontal*50,
child: Theme(
data: Theme.of(context).copyWith(canvasColor: const Color(0xFF2b4849)),
child: Drawer(
child: ListView(
children: <Widget>[
ListTile(
title: Text(
'Top News',
style: TextStyle(
fontSize: 20,
color: Colors.white
),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => NewsfeedForOtherCategory(216, 5, "Top News")
)
);
},
),
],
),
),
),
);
}
}
In my home screen which is newsfeed_screen.dart called in the body of AfterSplashState widget in main.dart it looks like below, this is what it should look like.
But in the screen NewsfeedForOtherCategory to which I navigate using drawer looks like below with the black background.
I have tried using Navigator.of(context, rootNavigator: true).pushNamed('/route') and pushReplacementNamed() also instead of MaterialPageRoute. But of no use.
Here is a related question that I found, I tried the solutions they gave, but did not work for me.
Also to mention, the page I'm navigating to does not have MaterialApp widget, only the main.dart has it. So there should not be an issue.
I'm using a Ubuntu 16.04 machine.
Some clue from you would be priceless. Thanks a lot for your time.
NewsfeedForOtherCategory page is black because it doesn't have Material container.
You can simply wrap it with Material widget or Scaffold(which has some additional features like drawer, floating action button).
And from your screenshot I can see some widgets are overflowed by notification bar. You can use SafeArea inside Material or inside body of the Scaffold to overcome this.
Wrap the main Container in NewsfeedForOtherCategory with a scaffold and you have your solution.
...
return Scaffold(
body: Container(
alignment: Alignment.center,
child: !_isRequestSent
? CircularProgressIndicator()
: Container(
child: ListView.builder(
itemCount: newsPostList.length,
scrollDirection: Axis.vertical,
itemBuilder: (BuildContext context, int index) {
return _getNewsPostWidgets(index);
}
),
),
);
);
...
In the build function of your NewsfeedForOtherCategory widget,
try wrapping what you have there in a Scaffold.
Like:
return Scaffold(
body: Container(
alignment: Alignment.center,
child: !_isRequestSent
? CircularProgressIndicator()
: Container(
child: ListView.builder(
itemCount: newsPostList.length,
scrollDirection: Axis.vertical,
itemBuilder: (BuildContext context, int index) {
return _getNewsPostWidgets(index);
}),
),
),
),
when we navigate between two screen both screen parent should be scafold
if you don't want to use scaffold u can use container color property also
Try wrapping your container in scaffold in NewsfeedForOtherCategory screen Like this
...
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
),
);
}
...
Or u can set container color white like this
...
#override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child:
//enter code here
);
}
...
I am trying to create a custom marker using asset image/ network image. I take that image and create a widget to do necessary styling and then I try to call MarkerGenerator which return a List<Uint8List>
MarkerGenerator. But I get the Uint8List without the asset image. I think the rendering of asset image is not completed before the MarkerGenerator was called. How can I call the MarkerGenerator after the completion of rendering assetImage.
import 'dart:typed_data';
import 'marker_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class MyMarkerPage extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _MyMarkerPageState();
}
}
class _MyMarkerPageState extends State<MyMarkerPage> {
Uint8List imageInMemory;
List<Uint8List> markerImage;
#override
void initState() {
super.initState();
List<Widget> widgetList = new List();
for (int i = 0; i < 1; i++) {
widgetList.add(
Container(
height: 50,
width: 50,
padding: EdgeInsets.all(10),
color: Colors.green,
child: Image.asset("assets/myImage.jpg"),
),
);
}
MarkerGenerator(widgetList, (bitmaps) {
setState(() {
markerImage = bitmaps;
});
}).generate(context);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Widget To Image'),
),
body: SingleChildScrollView(
child: Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
markerImage != null
? Container(
child: Image.memory(markerImage[0]),
margin: EdgeInsets.all(10))
: Container(),
],
),
),
),
);
}
}
The solution would be to wrap the MarkerGenerator.generate content in Future.delayed with 50ms. You could also try another timing.
Future.delayed(Duration(milliseconds: 50), () {
WidgetsBinding.instance
.addPostFrameCallback((_) => afterFirstLayout(context));
});