Flutter - how to add a widget to an Android view - android

Is it possible to add a Flutter widget or UI element to an Android View?
I am developing an Android SDK, where I work only with views and not activities or fragments
I get the view instance in a View.OnAttachStateChangeListener :
override fun onViewAttachedToWindow(view: View) {
}
override fun onViewDetachedFromWindow(view: View) {
}
and the view layout is a simple LinearLeayout or FrameLayout
I want to add a Flutter .arr to the project and display a widget inside the view. moreover I would want all the routes and UI that comes with the widget.
example, display the basic example from Flutter in a view and not in an activity, can it be done?
import 'package:flutter/material.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 _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.
);
}
}

I think you can't just add a Widget or any UI element from Flutter SDK into an Android View. Flutter Widgets need flutter context and flutter engine to work.
But, you can launch Flutter View into android native app https://flutter.dev/docs/development/add-to-app

Related

How to download files in WebView Flutter

I'm trying to download a file through webview_flutter, but the file won't download.
I've already got permissions to read and write to disk, but file download is nowhere to be found.
I expected the file to be downloaded to android. Can't find anything on downloading files in webview_flutter docs. I have tried alternate packages, but their solutions are messy or deprecated.
What is the standard way to download files from WebView in Flutter?
main.dart:
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.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(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// 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
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) {
// Update loading bar.
},
onPageStarted: (String url) {},
onPageFinished: (String url) {},
onWebResourceError: (WebResourceError error) {}
),
)
..loadRequest(Uri.parse('https://file-examples.com/index.php/sample-documents-download/sample-pdf-download/'));
#override
Widget build(BuildContext context) {
Permission.storage.request();
// 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(title: const Text('Flutter Simple Example')),
body: WebViewWidget(controller: controller),
);
}
}

A number doesn't change after updating it in setState(), it is called in a constructor

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);
}

FlutterView isn't displaying Widget UI in Android

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

How to get files from external storage in Flutter?

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.

How to show html string in text widget flutter

How to show html tag string in flutter, i have tried a plugin and its not working.
new HtmlView(
data: html,
baseURL: "", // optional, type String
onLaunchFail: (url) { // optional, type Function
print("launch $url failed");
}
This is my html
“Follow<a class='sup'><sup>pl</sup></a> what was sent down to you from your Lord, and do not follow other guardians apart from Him. Little do <span class='h'>you remind yourselves</span><a class='f'><sup f=2437>1</sup></a>.”
i user flutter_html_view: "^0.5.10" this plugin
This plugin doesn`t have any issue, I just created a sample with your HTML and it works fine. Try to replace with below snippet and see if that works.
dependencies:
flutter_html: ^0.8.2
and imports and code to render html
import 'package:flutter_html/flutter_html.dart';
import 'package:html/dom.dart' as dom;
body: new Center(
child: SingleChildScrollView(
child: Html(
data: """
<div>Follow<a class='sup'><sup>pl</sup></a>
Below hr
<b>Bold</b>
<h1>what was sent down to you from your Lord</h1>,
and do not follow other guardians apart from Him. Little do
<span class='h'>you remind yourselves</span><a class='f'><sup f=2437>1</sup></a></div>
""",
padding: EdgeInsets.all(8.0),
onLinkTap: (url) {
print("Opening $url...");
},
customRender: (node, children) {
if (node is dom.Element) {
switch (node.localName) {
case "custom_tag": // using this, you can handle custom tags in your HTML
return Column(children: children);
}
}
},
),
),
)
I've just done the followings and it works fine.
Add flutter_html to your pubspec.yaml file.
dependencies:
flutter:
sdk: flutter
flutter_html: ^0.8.2
Run the following command to update packages.
flutter pub get
Import flutter_html
import 'package:flutter_html/flutter_html.dart';
Replace Text widget with Html widget.
child:
// Text(
// "Hello Programmer",
// style: TextStyle(fontSize: 18),
// ),
Html(data:"<p>Hello <b>Flutter</b><p>"),
Do not use flutter_html_view that reading at the documentation:
Supported Tags
p
em
b
img
video
h1,
h2,
h3,
h4,
h5,
h6
Note
This plugin converts some of the html tags to flutter widgets This plugin does't support rendering full html code (there is no built in
support for web rendering in flutter)
So it simply doesn't render well your html because it can't.
But you could find other pulugins, like flutter_html
https://github.com/Sub6Resources/flutter_html
and give them a try in order to see if they perform better.
UPDATE
In pubspec.yaml I've add
dependencies:
flutter_html: ^0.8.2
and my main.dart is
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
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;
var html = "Follow<a class='sup'>pl</a> what was sent down to you from your Lord, and do not follow other guardians apart from Him. Little do <p class='h'>you remind yourselves</p><a class='f'><sup f=2437>1</a>.";
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 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>[
Html(
data: html,
),
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.
);
}
}
Add the following to your pubspec.yaml file:
dependencies:
flutter_html:
Currently Supported HTML Tags:
a, abbr, acronym, address, article, aside, b, bdi, bdo, big, blockquote, body, br, caption, cite, code, data, dd, del, dfn, div, dl, dt, em, figcaption, figure, footer, h1, h2, h3, h4, h5, h6, header, hr, i, img, ins, kbd, li, main, mark, nav, noscript, ol, p, pre, q, rp, rt, ruby, s, samp, section, small, span, strike, strong, sub, sup, table, tbody, td, template, tfoot, th, thead, time, tr, tt, u, ul, var
Example Usage:
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
new Html(
data: "<b>Welcome</b>,
defaultTextStyle: TextStyle(fontSize: 15),
),
],
)
all the packages mentioned from other answers are no longer maintained ( at least when I write this answer), it will create conflict to other packages I use which has recent update, I end up using this package: flutter_widget_from_html (ps: it is not mine)
Use flutter_webview_plugin plugin
example:
new WebviewScaffold(
url: new Uri.dataFromString('<html><body>hello world</body></html>', mimeType: 'text/html').toString()
Webview inside custom Rectangle
final flutterWebviewPlugin = new FlutterWebviewPlugin();
flutterWebviewPlugin.launch(url,
fullScreen: false,
rect: new Rect.fromLTWH(
0.0,
0.0,
MediaQuery.of(context).size.width,
300.0,
),
);
In the pubspec.yml add the following:
dependencies:
flutter_html:
Then run:
flutter clean && flutter pub get
Finally, add the code like this:
import 'package:flutter_html/flutter_html.dart';
.
.
.
body: Center( Html(
data: """
<div>This is the start of a div
<a class='sup'><sup>a sup</sup></a>
and after sub
<b>Bold</b>
<h1>This is a header with number 1557</h1>
A text and
<span class='h'>some stuff</div>
""",
),)
Until now, it works fine on both mobile and web.
might be a little late but i've made a project that accepts and tags
so you can do this
HTMLText('<b><i>SOME VERY IMPORTANT TEXT</i></b>');
and it'll translate your HTML into flutter based widgets and respect dark/light theme colors as well.
https://github.com/forumics/flutter-html-text
if you have list of object and need to groupBy you can use following link:
groupBy_in_flutter

Categories

Resources