I want to get all file in listview with flutter project but how to access the external folder.
I have created a folder with name 'MyFile' and it is created at "/storage/emulated/0/MyFile",
but below code pointing at "/storage/emulated/0/Android/data/com.example.demo/MyFile".
I don't know why below code is not working
Directory externalDirectory = await getExternalStorageDirectory();
print('External Storage:$externalDirectory');
// External storage: /storage/emulated/0/Android/data/com.example.demo/MyFile
When using Flutter Official path_provider package, getExternalStorageDirectory() will always return path to /storage/emulated/0/your-package-name/files.
To get /storage/emulated/0/, you can used a Third-party package ext_storage. Below code will return your desired Directory path
var externalDirectoryPath = await ExtStorage.getExternalStorageDirectory();
print(path); // /storage/emulated/0
Now to create a Folder, you can use the below function:
//this will create a Folder in the storage/emulated/0
new Directory(externalDirectoryPath +'/YourfolderName')
.create()
.then((Directory directory)
{
print(directory.path);
});;
'
Edit post picture 2 to prove it work.
code snippet to create directory , file
new Directory('/storage/emulated/0/MyFile').create()
// The created directory is returned as a Future.
.then((Directory directory) {
print(directory.path);
});
new File('/storage/emulated/0/MyFile/test.txt').create(recursive: true)
.then((File file) {
// Stuff to do after file has been created...
print('${file.path}');
});
var dir = Directory('/storage/emulated/0/MyFile');
print('${dir.path}');
print('${dir.list().toList()}');
full code for create directory and file
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:simple_permissions/simple_permissions.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: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
new Directory('/storage/emulated/0/MyFile').create()
// The created directory is returned as a Future.
.then((Directory directory) {
print(directory.path);
});
new File('/storage/emulated/0/MyFile/test.txt').create(recursive: true)
.then((File file) {
// Stuff to do after file has been created...
print('${file.path}');
});
var dir = Directory('/storage/emulated/0/MyFile');
print('${dir.path}');
print('${dir.list().toList()}');
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
SimplePermissions.requestPermission(Permission.WriteExternalStorage);
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
please use package flutter_file_manager https://pub.dev/packages/flutter_file_manager
I have tested with real device, it works fine
full code
// framework
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
// packages
import 'package:flutter_file_manager/flutter_file_manager.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;
import 'package:simple_permissions/simple_permissions.dart';
void main() => runApp(new MyApp());
#immutable
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
//SimplePermissions.requestPermission(Permission.ReadExternalStorage);
SimplePermissions.requestPermission(Permission.WriteExternalStorage);
return new MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Flutter File Manager Demo"),
),
body: FutureBuilder(
future: _files(), // a previously-obtained Future<String> or null
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Press button to start.');
case ConnectionState.active:
case ConnectionState.waiting:
return Text('Awaiting result...');
case ConnectionState.done:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
return snapshot.data != null
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) => Card(
child: ListTile(
title: Column(children: [
Text('Size: ' +
snapshot.data[index]
.statSync()
.size
.toString()),
Text('Path: ' +
snapshot.data[index].path.toString()),
Text('Date: ' +
snapshot.data[index]
.statSync()
.modified
.toUtc()
.toString())
]),
subtitle: Text(
"Extension: ${p.extension(snapshot.data[index].absolute.path).replaceFirst('.', '')}"), // getting extension
)))
: Center(
child: Text("Nothing!"),
);
}
return null; // unreachable
},
)),
);
}
_files() async {
var root = await getExternalStorageDirectory();
var files = await FileManager(root: root).walk().toList();
for(var i = 0;i<files.length;i++) {
print("${files[i].path} ");
}
return files;
}
}
working demo in emulator
I had the same problem, while Android SDK version >30 or 31 doesn't allow to read from other directories but you definitely read from your directory without any permission.
Add '//' + directory path & your problem will be resolved
So it means that your path will be '//'+ getExternalStorageDirectory())!.path
This is the code to save and retrieve the file work on both SDK > 30 and SDK =< 30.
final directory = (await getExternalStorageDirectory())!.path;
ByteData? byteData =
await (image.toByteData(format: ui.ImageByteFormat.png));
Uint8List pngBytes = byteData!.buffer.asUint8List();
File imgFile = new File('$directory/screenshot${rng.nextInt(2000)}.png');
await imgFile.writeAsBytes(pngBytes);
setState(() {
_imageFile = imgFile;
});
// Add '//' + directory path & your problem will be resolved
return '//'+imgFile.path;
First I'm saving the image in the directory then I'm reading it.
Related
I am trying to share a file using SharePlus. However, I get the following error:
The task is to generate a PDF file and share it through ios and android. I see that share_plus is able to share the file. However, I am unable to share by saving it in the applicationDocumentDirectory.
Update: I have attached a demo repo with codes from below. The error is showing in my app even when the repo is working without permissions fine. share_plus complains with below issues.
Repo: Link
Error:
Unhandled Exception: PlatformException(error, Failed to find configured root that contains /data/user/0/com.example.flutter_share_demo/app_flutter/someRandom.pdf, null, java.lang.IllegalArgumentException: Failed to find configured root that contains /data/user/0/com.example.flutter_share_demo/app_flutter/someRandom.pdf
The code is as follows:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:permission_handler/permission_handler.dart';
import 'package:share_plus/share_plus.dart';
void main() {
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) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Share files')),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: TextButton(
child: const Text('Generate and Share PDF'),
onPressed: () async {
final pdf = pw.Document();
pdf.addPage(pw.Page(
build: (context) =>
pw.Center(child: pw.Text('Hello, World!')),
));
final Directory storageDir = getApplicationDocumentDirectory();
try {
File file = File('${storageDir.path}/someRandom.pdf');
await file.writeAsBytes(await pdf.save());
print(file.path);
print('File exists: ${await file.exists()}');
Share.shareFiles([file.path], subject: 'Shared file');
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Permission denied')));
}
} on PlatformException catch (ex) {
print(ex);
} catch (ex) {
print(ex);
}
},
),
),
],
));
}
}
This question already has answers here:
How to take a screenshot of the current widget - Flutter
(4 answers)
Closed 2 years ago.
How can I implement the in-app screenshot functionality in flutter android?
I need this function to take a screenshot of the app screen and share the picture.
are there any plugins?
I have shared an example of code where I have used Screenshot plugin available on pub.dev along with permission handler and path provider plugin. Basically this plugin wraps your widgets inside RenderRepaintBoundary and creates an screenshot of your widget.
main.dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:screenshot/screenshot.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Screenshot Demo Home Page'),
);
}
}
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;
File _imageFile;
//Create an instance of ScreenshotController
ScreenshotController screenshotController = ScreenshotController();
#override
void initState() {
// TODO: implement initState
super.initState();
_requestPermission();
}
_requestPermission() async {
Map<Permission, PermissionStatus> statuses = await [
Permission.storage,
].request();
final info = statuses[Permission.storage].toString();
print(info);
}
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Container(
child: new Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Screenshot(
controller: screenshotController,
child: Column(
children: <Widget>[
Text(
'You have pushed the button this many times:' +
_counter.toString(),
),
FlutterLogo(),
],
),
),
_imageFile != null ? Image.file(_imageFile) : Container(),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
_incrementCounter();
_imageFile = null;
screenshotController
.capture(delay: Duration(milliseconds: 10))
.then((File image) async {
//print("Capture Done");
setState(() {
_imageFile = image;
});
final result =
await ImageGallerySaver.saveImage(image.readAsBytesSync());
print("File Saved to Gallery $result");
}).catchError((onError) {
print("Error: $onError");
});
},
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
_saved(File image) async {
final result = await ImageGallerySaver.saveImage(image.readAsBytesSync());
print("File Saved to Gallery");
}
}
Packages used:
screenshot:
image_gallery_saver: ^1.1.0
permission_handler:
path_provider: ^1.6.24
You will need to specify storage permissions in AndroidManifest file as below:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
To take screenshots within flutter app of the current use this screenshot package it also has example and documentation for saving the image to a folder and as well as to gallery which can also be google photos using 2 other plugins which you can find there only. I have used this plugin and it works really well if you havep any queries then you can comment below. Hope this helps you out!
Context
I have an application in Kotlin (native Android) and it sends data to an attached module in Flutter. From Kotlin I send _numA2F, and I want to show it on flutter view, but it isn't working. The other variable (_numF2A) that I'm going to send back to the native app is getting updated properly.
Question
Could you please point out why _numA2F isn't taking the value received from the native android application? I already confirmed that the number that I send from Kotlin is received in the flutter module.
This is my code in Flutter:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.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: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or press Run > Flutter Hot Reload in a Flutter IDE). Notice that the
// counter didn't reset back to zero; the application is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _numA2F = 1;
int _numF2A = 1;
static const platform = const MethodChannel('com.jssm.af/data');
_MyHomePageState() {
platform.setMethodCallHandler(_receiveFromHost);
}
Future<void> _receiveFromHost(MethodCall call) async {
int number = 11;
try {
print('CHECK THIS OUT!!!!!!!!!');
print(call.method);
if (call.method == "fromHostToClient") {
final String data = call.arguments;
print(call.arguments);
final jData = jsonDecode(data);
number = jData['numA2F'];
}
} on PlatformException catch (e) {
print(e);
}
setState(() {
_numA2F = number;
print("_numberA2F: " + _numA2F.toString());
});
}
void _doubleNumber() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_numF2A = 2 * _numA2F;
});
}
#override
Widget build(BuildContext context) {
print('REBUILDING!!!!!!!!!!');
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Data received from fa_Android',
),
Text(
'$_numA2F',
style: Theme.of(context).textTheme.headline4,
),
Text(
'Number to be returned (double):',
),
Text(
'$_numF2A',
style: Theme.of(context).textTheme.headline4,
),
RaisedButton(
onPressed: _doubleNumber,
child: const Text('Send Result to Android',
style: TextStyle(fontSize: 20)),
)
],
),
),
);
}
}
Remove this:
_MyHomePageState() {
platform.setMethodCallHandler(_receiveFromHost);
}
And use an initState function like this:
#override
void initState() {
_receiveFromHost(call);
}
or better still use:
_MyHomePageState() {
_receiveFromHost(call);
}
I have an android SDK that integrates a Flutter module. the Dart code is the basic increment example from Flutter.
I am trying to load the Dart code into a FlutterView. I notice though a print the Dart code is called, but the widget is not displayed
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical">
<io.flutter.embedding.android.FlutterView
android:id="#+id/flutter_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
the code that loads the dart code (in a View.OnAttachStateChangeListener):
override fun onViewAttachedToWindow(v: View?) {
v?.run {
FlutterMain.startInitialization(context)
FlutterMain.ensureInitializationComplete(context,null);
val flutterEngine = FlutterEngine(context)
flutterEngine.dartExecutor.executeDartEntrypoint(
// set which of dart methode will be used here
DartExecutor.DartEntrypoint(FlutterMain.findAppBundlePath(), "myMainDartMethod")
// to set here the main methode you can use this function to do this
// inteade of DartEntrypoint(FlutterMain.findAppBundlePath(),"myMainDartMethod")
// write this mdethode DartEntrypoint.createDefault()
//DartExecutor.DartEntrypoint.createDefault()
)
flutterView = findViewById(R.id.flutter_view)
flutterView.attachToFlutterEngine(flutterEngine)
}
}
I have used "myMainDartMethod" and DartExecutor.DartEntrypoint.createDefault() both don't work
the dart code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
#pragma('vm:entry-point') // say the release that this function must alos in the project used and it must not deleted
void myMainDartMethod() => runApp(MyApp()); // I use this function to show in the android activity
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
print("Flutter/MyApp in dart is called");
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or press Run > Flutter Hot Reload in a Flutter IDE). Notice that the
// counter didn't reset back to zero; the application is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
notice the print, which is actually being called but the UI is not visible in the Android side (FlutterView).
What am I missing? What can I add/change to display the code?
the problem was I was missing lifecycleChannel state.
I have added the following line right after the instantiation of FlutterEngine
val flutterEngine = FlutterEngine(context)
flutterEngine.lifecycleChannel.appIsResumed()
of course, you will probably need to call other lifecycleChannel methods in the correct place
source: https://medium.com/#kassan424/sample-example-how-flutterview-in-a-android-activity-can-be-use-b9a887cd1d7
So I want to set the children of my GridView dynamically so I can set it when I want. Currently this is the whole class.
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/CustomColors.dart';
import 'package:flutter_app/quote/Quote.dart';
import 'package:flutter_app/quote/QuoteView.dart';
import 'package:flutter_app/section/Section.dart';
import 'package:flutter_app/quote/QuoteData.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
static List<QuoteData> data = [];
_readJson() async {
data.clear();
var url = 'https://www.dropbox.com/s/7k280ca5dktlhoo/quotes.json?dl=1';
var httpClient = new HttpClient();
httpClient.getUrl(Uri.parse(url)).then((HttpClientRequest request) {
return request.close();
}).then((HttpClientResponse response) {
response.transform(utf8.decoder).listen((contents) {
List<Map> decoded = JSON.decode(contents);
decoded.forEach((m) {
String url = m["url"];
String title = m["title"];
String sectionString = m["section"];
Section section;
for (Section element in Section.values) {
if (element.toString() == "Section." + sectionString) {
section = element;
}
}
List<Quote> quotes = m["quotes"];
data.add(new QuoteData(url, title, section, quotes));
});
});
});
}
#override
Widget build(BuildContext context) {
_readJson();
return new MaterialApp(
title: 'Quotes',
theme: new ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or press Run > Flutter Hot Reload in IntelliJ). Notice that the
// counter didn't reset back to zero; the application is not restarted.
primarySwatch: CustomColors.black,
),
home: new MyHomePage(title: 'Quotes'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static Section currentSection = Section.movies;
void _onTileClicked(QuoteData quote) {
Navigator.push(context,
new MaterialPageRoute(builder: (context) => new QuoteView(quote)));
}
List<Widget> _getTiles(Section section) {
final List<Widget> tiles = <Widget>[];
for (var i in MyApp.data) {
if (i.section != section) {
continue;
}
tiles.add(new GridTile(
child: new InkResponse(
enableFeedback: true,
child: new Image.network(
i.url,
fit: BoxFit.cover,
),
onTap: () => _onTileClicked(i),
)));
}
return tiles;
}
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
final double itemHeight = (size.height - kToolbarHeight - 24) / 2;
final double itemWidth = size.width / 2;
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return new Scaffold(
appBar: new AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: new Text(currentSection
.toString()
.replaceAll("Section.", "")
.substring(0, 1)
.toUpperCase() +
currentSection.toString().replaceAll("Section.", "").substring(1)),
),
body: new Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: new GridView.count(
crossAxisCount: 2,
childAspectRatio: (itemWidth / itemHeight),
padding: const EdgeInsets.all(4.0),
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: _getTiles(currentSection)),
),
);
}
}
So right now on startup, it launches the application but MyApp.data is empty because the json has to be read so the GridView will be empty, when I refresh the application, the GridView won't be empty because MyApp.data won't be empty anymore. I want to be able to set the children after the json gets read, also I need to be able to change it dynamically because I will add a function for switching sections.
The same goes for the title, I also need to be able to change it dynamically when switching sections.
You can create a loading widget and wait for the request to finish when the request is finished hide the loading and show the grid than rebuild the state. but you need to have a statefullWidget not statelessWidget.
You can see how i use it on the code below I added my comments to the code
class _ChildrenPageState extends State<ChildrenPage> {
//declare the _load to true so it will show the loading when the page is loaded
bool _load = true;
ChildrenService _childrenService = new ChildrenService();
List children = [];
//I call the _rebuild function to rebuild the widgets and show the data
void _rebuild() {
setState(() {
});
}
#override
Widget build(BuildContext context) {
//I call the request to get my data when it is finished i put _load to false so the loading will hide and call the _rebuild function to rebuild the widgets and i have put if so when the widget is built it will not rebuild it a second time.
_childrenService.getChildren(children).then((data){
if(data && _load){
_load = false;
_rebuild();
}
});
//the below widget show the loading container if _load is true else it will show the dataTable in your app you should add the grid and you can pass the data that you got from the request
Widget loadingIndicator = _load ? new Container(
color: Colors.grey[300],
width: 70.0,
height: 70.0,
child: new Padding(
padding: const EdgeInsets.all(5.0),
child: new Center(
child: new CircularProgressIndicator()
)
),
) : new JLDataTable(
data: children,
);
return new Scaffold(
drawer: new Drawer(
child: MenuList.menuList,
),
appBar: new AppBar(title: const Text('Data tables')),
body: new ListView(
padding: const EdgeInsets.all(20.0),
children: <Widget>[
new Align(
child: loadingIndicator,
alignment: FractionalOffset.center
)
]
)
);
}
}