How do I use a builder function? - flutter - user-interface

I have asked a question named 'How to inject a Widget into a custom child Widget and use the child Widgets iteration index?' I already got an answer but there is a problem.
The answer said that I should:
"Instead of passing a Widget to your custom AppList you could pass a builder function that returns a Widget and takes the parameters as required, e.g. the index and whatever configuration is required. Something like the following:
Function definition:
typedef Widget MyListTileBuilder(String tileText);
then change the following:
final Widget child;
to
final MyListTileBuilder childBuilder;
of course you need to implement your builder method in Example Class:
Widget MyListTileBuilderImplementation (int index) {
return ListTile (
title: Text(installedApps[index]["app_name"]) //this is the text
),
}
when you build AppList inside example class you pass the method
AppList (
childBuilder: MyListTileBuilderImplementation
)
and finally inside AppList you call the builder, instead of adding child widget" :
itemBuilder: (context, index) {
return childBuilder(index); //This is where the ListTile will go.
},
So, I tried to edit my code. But for some reason it was not working. I think that I'm doing it wrong. Does anybody know how to solve this problem? (It would be very very helpful if you could edit my full code.)
Full Code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'dart:io';
import 'package:flutter_appavailability/flutter_appavailability.dart';
void main() {
SystemChrome.setEnabledSystemUIOverlays([]);
runApp(Example());
}
Future<void> getApp() async {
if (Platform.isAndroid) {
installedApps = await AppAvailability.getInstalledApps();
print(await AppAvailability.checkAvailability("com.android.chrome"));
print(await AppAvailability.isAppEnabled("com.android.chrome"));
}
else if (Platform.isIOS) {
installedApps = iOSApps;
print(await AppAvailability.checkAvailability("calshow://"));
}
}
List<Map<String, String>> installedApp;
List<Map<String, String>> installedApps;
List<Map<String, String>> iOSApps = [
{
"app_name": "Calendar",
"package_name": "calshow://"
},
{
"app_name": "Facebook",
"package_name": "fb://"
},
{
"app_name": "Whatsapp",
"package_name": "whatsapp://"
}
];
class Example extends StatefulWidget {
#override
ExampleState createState() => ExampleState();
}
class ExampleState extends State<Example> {
#override
Widget build(BuildContext context) {
return MaterialApp (
debugShowCheckedModeBanner: false,
home: Scaffold (
body: Container (
color: Colors.black,
child: AppList ()
)
),
);
}
}
class AppList extends StatefulWidget {
#override
AppListState createState() => AppListState();
AppList({Key key, this.child}) : super(key: key);
final Widget child;
}
class AppListState extends State<AppList> {
Widget child;
List<Map<String, String>> _installedApps;
#override
void initState() {
super.initState();
}
getApps() {
setState(() {
installedApps = _installedApps;
getApp();
});
}
#override
Widget build(BuildContext context) {
if (installedApps == null)
getApps();
return ListView.builder(
itemCount: installedApps == null ? 0 : installedApps.length,
itemBuilder: (context, index) {
return ListTile (
title: Text(installedApps[index]["app_name"])
);
},
);
}
}

This is your example with the changes:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'dart:io';
//import 'package:flutter_appavailability/flutter_appavailability.dart';
typedef Widget MyListTileBuilder(int index);
void main() {
SystemChrome.setEnabledSystemUIOverlays([]);
runApp(Example());
}
Future<void> getApp() async {
if (Platform.isAndroid) {
//installedApps = await AppAvailability.getInstalledApps();
//print(await AppAvailability.checkAvailability("com.android.chrome"));
//print(await AppAvailability.isAppEnabled("com.android.chrome"));
}
else if (Platform.isIOS) {
installedApps = iOSApps;
//print(await AppAvailability.checkAvailability("calshow://"));
}
}
List<Map<String, String>> installedApp;
List<Map<String, String>> installedApps=[
{"app_name":"app1"},
{"app_name":"app2"},
{"app_name":"app3"},
];
List<Map<String, String>> iOSApps = [
{
"app_name": "Calendar",
"package_name": "calshow://"
},
{
"app_name": "Facebook",
"package_name": "fb://"
},
{
"app_name": "Whatsapp",
"package_name": "whatsapp://"
}
];
class Example extends StatefulWidget {
#override
ExampleState createState() => ExampleState();
}
class ExampleState extends State<Example> {
Widget MyListTileBuilderImplementation (int index) {
return ListTile (
title: Text(installedApps[index]["app_name"] + " index:" + index.toString()) //this is the text
);
}
#override
Widget build(BuildContext context) {
return MaterialApp (
debugShowCheckedModeBanner: false,
home: Scaffold (
body: Container (
color: Colors.white,
child: AppList (childBuilder: this.MyListTileBuilderImplementation)
)
),
);
}
}
class AppList extends StatefulWidget {
#override
AppListState createState() => AppListState();
AppList({Key key, this.childBuilder}) : super(key: key);
final MyListTileBuilder childBuilder;
}
class AppListState extends State<AppList> {
List<Map<String, String>> _installedApps;
#override
void initState() {
super.initState();
}
getApps() {
setState(() {
installedApps = _installedApps;
getApp();
});
}
#override
Widget build(BuildContext context) {
if (installedApps == null)
getApps();
return ListView.builder(
itemCount: installedApps == null ? 0 : installedApps.length,
itemBuilder: (context, index) {
return widget.childBuilder(index);
},
);
}
}

Related

Exception has occurred. _ClientSocketException (Failed host lookup: 'flutter-api.test')

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Category{
int id;
String name;
Category({
required this.id,
required this.name
});
factory Category.fromJson(Map<String, dynamic> json) {
return Category(id: json['id'], name:json['name']);
}
}
class Categories extends StatefulWidget {
const Categories({super.key});
#override
CategoriesState createState() => CategoriesState();
}
class CategoriesState extends State<Categories> {
late Future<List<Category>> futureCategories;
Future<List<Category>> fetchCategories() async {
http.Response response = await http.get(
Uri.parse('http://flutter-api.test/api/categories')
);
List categories = jsonDecode(response.body);
return categories.map((category) => Category.fromJson(category)).toList();
}
#override
void initState() {
super.initState();
futureCategories = fetchCategories();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Categories'),
),
body: FutureBuilder<List<Category>>(
future: futureCategories,
builder: (context, snapshot) {
if(snapshot.hasData){
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
Category category = snapshot.data![index];
return ListTile(
title: Text(category.name)
);
},
);
}else if(snapshot.hasError){
return const Text('Something went wrong');
}
return const CircularProgressIndicator();
}
)
);
}
}
This flutter app requests the laravel api to provide a list of categories from
http://flutter-api.test/api/categories
I ran my flutter app in my local environment and it worked well using the chrome browser(List of categories appeared)
However, it didn't work when i ran it through the android emulator.
It gives the below error
Exception has occurred.
_ClientSocketException (Failed host lookup: 'flutter-api.test')
I have already entered
<uses-permission android:name="android.permission.INTERNET" />
in AndroidManifest.xml file

Flutter RawKeyboardListener and 2D hardware scanner returns random result in Windows app

I generate QR code with free text (53a7a000-958c-11ec-0a80-085a0034aec2) and scanning it in a Flutter Windows app with hardware 2d scanner. But it constantly returns wrong text. It can be less or wrong characters. But at the same time I'm running the same code in android app and it works perfect.
Here is code i'm using
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'RawKeyboardListener';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatefulWidget(),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
final FocusNode _focusNode = FocusNode();
String _controller = '';
String? _message;
#override
void dispose() {
_focusNode.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
FocusScope.of(context).requestFocus(_focusNode);
final TextTheme textTheme = Theme.of(context).textTheme;
return Container(
color: Colors.white,
alignment: Alignment.center,
child: DefaultTextStyle(
style: textTheme.bodyText1!,
child: RawKeyboardListener(
focusNode: _focusNode,
onKey: (RawKeyEvent event) {
if (event is RawKeyDownEvent) {
if (event.physicalKey == PhysicalKeyboardKey.enter) {
print('ENTER');
setState(() {
_message = _controller;
_controller = '';
});
} else {
print(
'_handleKeyEvent Event data keyLabel ${event.data.keyLabel}');
_controller += event.data.keyLabel;
}
print('controller: $_controller');
}
},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
_message ?? 'Press a key',
),
Text(
'${_message?.length}',
),
],
),
),
),
);
}
}

How to decode Base64 String to Image file with flutter

I am actually trying to convert an Image file to Base64 and decode Base64 String to Image file in Dart/Flutter. Indeed, my application takes pictures with the camera plugin and then, saves it in a database as a Base64 String (because I don't know any other way but may be there is more relevant ways to store several images?).
I encode with this code :
final path = join(
(await getTemporaryDirectory()).path,
'${DateTime.now()}.png',
);
await _controller.takePicture(path);
final bytes = File(path).readAsBytesSync();
String img64 = base64Encode(bytes);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DisplayPictureScreen(imageAnalysed: img64),
),
);
And decode with this one :
class DisplayPictureScreen extends StatelessWidget {
final String imageAnalysed;
const DisplayPictureScreen({Key key, this.imageAnalysed}) : super(key: key);
#override
Widget build(BuildContext context) {
final decodedBytes = base64Decode(imageAnalysed);
var fileImg= File("testImage.png");
fileImg..writeAsBytesSync(decodedBytes);
return Scaffold(
appBar: AppBar(title: Text('Display the Picture')),
body: Image.file(fileImg),
);
}
}
But there is this error :
The following FileSystemException was thrown building DisplayPictureScreen(dirty):
Cannot open file, path = 'testImage.png' (OS Error: Read-only file system, errno = 30)
How can I solve my problem and get an image from the Base64 String ?
Thank you for your help !
You can copy paste run full code below
You can use path_provider to get getApplicationDocumentsDirectory and use bool isLoading to control show image when write file finish
code snippet
void writeFile() async {
final decodedBytes = base64Decode(widget.imageAnalysed);
final directory = await getApplicationDocumentsDirectory();
fileImg = File('${directory.path}/testImage.png');
print(fileImg.path);
fileImg.writeAsBytesSync(List.from(decodedBytes));
setState(() {
isLoading = false;
});
}
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_){
writeFile();
});
...
#override
Widget build(BuildContext context) {
return isLoading ? CircularProgressIndicator() : Image.file(fileImg);
}
working demo
full code
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';
class DisplayPictureScreen extends StatefulWidget {
final String imageAnalysed;
const DisplayPictureScreen({Key key, this.imageAnalysed}) : super(key: key);
#override
_DisplayPictureScreenState createState() => _DisplayPictureScreenState();
}
class _DisplayPictureScreenState extends State<DisplayPictureScreen> {
File fileImg;
bool isLoading = true;
void writeFile() async {
final decodedBytes = base64Decode(widget.imageAnalysed);
final directory = await getApplicationDocumentsDirectory();
fileImg = File('${directory.path}/testImage.png');
print(fileImg.path);
fileImg.writeAsBytesSync(List.from(decodedBytes));
setState(() {
isLoading = false;
});
}
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_){
writeFile();
});
super.initState();
}
#override
Widget build(BuildContext context) {
return isLoading ? CircularProgressIndicator() : Image.file(fileImg);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter 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;
String base64String =
'''iVBORw0KGgoAAAANSUhEUgAAANIAAAAzCAYAAADigVZlAAAQN0lEQVR4nO2dCXQTxxnHl0LT5jVteHlN+5q+JCKBJITLmHIfKzBHHCCYBAiEw+I2GIMhDQ0kqQolIRc1SV5e+prmqX3JawgQDL64bK8x2Ajb2Bg7NuBjjSXftmRZhyXZ1nZG1eL1eGa1kg2iyua9X2TvzvHNN/Ofb2Z2ZSiO4ygZGZm+EXADZGSCgYAbICMTDATcABmZYCDgBsjIBAMBN0BGJhgIuAEyMsGA1wQdHZ1UV1cX5XK5qM7OzgcMRuNTrSbTEraq6strhdfzruTk5Wpz8q5c1l7Jyb6szc3K1l7RggtFxcWX2dvVB02mtmVOp3NIV2fnQFie2WyB5QS84TIy/YnXBFBI8BMM/pDqat0XzIVM08lTSVxyytn6jAuZV4FuzmtzclJz8/LT8vML0nJzr54HYkpLS88oTkxMMZ48mchlXrxUX1ffcBCUM8xms8lCkgk6pCT6aZvZvCrzYpbu2PfxHAg8l+obGmOt1vaJQBAPkvI5nM5fWyyWWTU1tfuA+IqOHDvGgehVCK4pA91oGZn+xluCAc0thtj4hCT72XOp9S0thi2FBQWPvb13z9RN61QH5s8NYxbMDct7KXyudt7MGeeWLFrwn8iVKz7auDZy3Z7d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NcKpNhPpWYxKWmpjeDZd0WtG4vjZORuRcoafEI2QO/hASXdAajUcozpEGF14uPpgPhWK22xRaLdUbV7eo3b9ws28+yVXsdDvtceHonC0nmPoShey89ien9jkjNLQaqrc1MxASw2donpaZn1JeVlyeBfdEv2232O/sjMe4DJ8r8+GDo7i8K4va1KrH8PgsJPkuC+yL4tgL8JAGPucvKK2MzM7PaWltbl4AyB/wvj10Wksz9CCeCaDSC+CQkGInq6utF90Q8oIzf5l0tuFheXvkPsI962HN6JwtJ5n6FofEiwn3hsxeShVQF9kVQRPDfSZKwN6Kampt3Xiu83mQymcL5a/BrE1BMspBk7kNUdO8TVeGJoCiShOR+DaiuTvKfFQbpHqmoqMzW6/WJ8PgbOQ6XkQlKsBd5IUFaDAbJkQhitdpWgKUg226zLYS/y0KS+TGAvdjc3OKmqamFamtroywWq+gpHY/ZbBnU3GL4FHx+A8r5BeEhrYxM0BFwA2RkgoGAGyAjEwwE3AAZmWAg4AbIyAQDATdARiYYCLgBMjLBQMANkJEJBgJugIxMMPBfChd6NRZ5pkMAAAAASUVORK5CYII=''';
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DisplayPictureScreen(imageAnalysed: base64String),
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),
),
);
}
}

How to show local string in StatefulWidget?

I've learned How to use i18n via StatelessWidget for my flutter practice,
but still not work via StatefulWidget.
I can simply replace the following code
title: new Text(S.of(context).title)
with a const String, for example:
title: const Text("A Test Title");
So I think every thing else should be okay. The only problem is i18n not work.
Could some body help me, "How to use i18n via StatefulWidget on flutter ?"
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'generated/i18n.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key key, this.title}) : super(key: key);
final String title;
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
BuildContext c;
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
var tiles = new List<Widget>();
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text(S.of(context).title), // Here is the problem
),
body: new Stack(
children: <Widget>[
new Container(),
new ListView(
children: tiles,
)
],
),
),
localizationsDelegates: [S.delegate],
supportedLocales: S.delegate.supportedLocales,
localeResolutionCallback: S.delegate.resolution(
fallback: new Locale("en", "")
),
);
}
}
The context you're using doesn't have a MaterialApp as a parent. Instead, it has a MaterialApp as a child.
The problem is, S instance you're trying to fetch using S.of(context) is stored inside MaterialApp. Hence the error.
What you can instead do is use a different context where that context has MaterialApp in its parents.
The easiest way to achieves this is by wrapping a part of your app into a Builder.
Something like :
return MaterialApp(
home: Builder(
builder: (context) {
const title = S.of(context).title; // works now because the context used has a MaterialApp inside its parents
return Scaffold(...);
}
)
)

Flutter - Routing between different Views

So, I have this file:
import 'package:flutter/material.dart';
import "calculateDerivations.dart";
import "calculateRoots.dart";
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Ableitungen berechnen'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text(config.title)),
body: new Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
new InputWidget(),
]
),
);
}
}
class InputWidget extends StatefulWidget {
#override
InputWidgetState createState() => new InputWidgetState();
}
class InputWidgetState extends State<InputWidget> {
InputValue val = new InputValue(text: "");
String ersteAbleitung = "";
String zweiteAbleitung = "";
String dritteAbleitung = "";
String roots = "";
String function = "";
void _submitted(){
setState((){
/*
* Redirect here
*/
});
}
#override
Widget build(BuildContext context) {
return new Column(
children: [
new Input(
value: val,
labelText: 'Funktion hier eingeben',
onChanged: (InputValue newInputValue) {
setState(() {
val = newInputValue;
});
}),
new IconButton(
icon: new Icon(Icons.check),
onPressed: _submitted,
)
]
);
}
}
As soon as the user now clicks the IconButton (which calls _submitted), I want him to be redirected to a new View (Widget). How would I solve this routing problem in Flutter?
Thanks in advance
Normal route navigation might look like this:
new IconButton(
icon: new Icon(Icons.check),
onPressed: () {
Navigator.push(context, new MaterialPageRoute(
builder: (_) => new MyCustomView(),
);
)
)
You can also use named routes by passing a map of WidgetBuilders as the routes constructor argument for your MaterialApp, or by passing an onGenerateRoute handler. There's an example of named routes in the Flutter gallery.
If you don't want there to be an animation, see my answer to this question.

Resources