Is there a way to fix the "Function expressions can't be named" error in Flutter? - flutter-web

I watched a video tutorial for learning flutter and I encountered an error using the map method, can you help me fix it?
This is the link of the video I watched and followed along : https://www.youtube.com/watch?v=x0uinJvhNxI&t=18425s
This is the code :
import 'package:flutter/material.dart';
import './question.dart';
import './answer.dart';
class Quiz extends StatelessWidget {
final List<Map<String, Object>> questions;
final int questionIndex;
final Function answerQuestion;
Quiz(\{required this.questions, required this.answerQuestion,required this.questionIndex});
#override
Widget build(BuildContext context) {
return Column(
children: [
Question(
questions[questionIndex]['questionText'] as String,
/* answerQuestion(Named function) is a pointer that is passed as a value to onPressed but not the result of the function name ;*/ // onpressed attribute requires a function
),
...(questions[questionIndex]['answers'] as List<Map<String,Object>>).map(answer){ //Creating a list of widgets
return Answer(() => answerQuestion(answer['score']),answer['text']); // Return a widget
}.toList() // Based on the old List, it creates a new List
],
);
}
}

Related

Flutter go router pass List dynamic to parameter

i was using go router for flutter app i can pass String parameters between activities and its working now i want to pass list dynamic and am getting error
The argument type 'String' can't be assigned to the parameter type
'List'. (Documentation)
Receiver activity have
class EditUserPage extends StatefulWidget {
final String name;
final List<dynamic> userinformation;
}
on Route builder i have passed my data like below
GoRoute(
path: 'editusers',
name:
'editusers/:name,:userinformation,'
builder: (BuildContext context, GoRouterState state) {
return EditUserPage(
state.params["name"]!,
state.params["userinformation"]!,
)
);
The error comes on this line state.params["userinformation"]!, The argument type 'String' can't be assigned to the parameter type 'List'.
You can use this method
step 1
class ScreenArguments{
final Key? key;
final List<dynamic> list;
final DateTime dateTime;
ScreenArguments({
this.key,
required this.list,
required this.dateTime,
});
}
step 2
builder: (context, state) {
return Screen(
arguments: state.extra as ScreenArguments,
);
},
step 3
final ScreenArguments arguments;
const Screen({
super.key,
required this.arguments,
});
step 4
context.pushNamed(
'name',
extra: ScreenArguments(
list:list,
dateTime: dateTime,
),
);

How to fix "Failed assertion: 'create != null': is not true" error with Provider package in Flutter?

Here is the error message from Android Studio:
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building MyZippyApp(dirty):
'package:provider/src/provider.dart': Failed assertion: line 181 pos 16: 'create != null': is not true.
The relevant error-causing widget was:
MyZippyApp file:///Users/mgav/AndroidStudioProjects/streakers_journal_beta/lib/main.dart:5:23
When the exception was thrown, this was the stack:
#2 new Provider (package:provider/src/provider.dart:181:16)
#3 MyZippyApp.build (package:streakers_journal_beta/main.dart:10:12)
#4 StatelessElement.build (package:flutter/src/widgets/framework.dart:4701:28)
#5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4627:15)
#6 Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)
It appears as soon as I wrap 'MaterialApp' in a 'Provider' widget (using package version provider: ^4.3.2 in pubspec.yaml > ran 'Pub get'), then try to run the app.
Here is the main.dart code before wrapping with the 'Provider' widget (works perfectly well):
import 'package:flutter/material.dart';
import 'package:streakers_journal_beta/screens/tasks_screen.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyZippyApp());
class MyZippyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home:
TasksScreen(), // matches "TasksScreen" class created on tasks_screen.dart
);
}
}
Here is the main.dart code after wrapping with the provider widget:
import 'package:flutter/material.dart';
import 'package:streakers_journal_beta/screens/tasks_screen.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyZippyApp());
class MyZippyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Provider(
child: MaterialApp(
home:
TasksScreen(), // matches "TasksScreen" class created on tasks_screen.dart
),
);
}
}
And per Farhan Syah's answer below, here is the revised code that reflects his answer (and fixes the problem):
import 'package:flutter/material.dart';
import 'package:streakers_journal_beta/screens/tasks_screen.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyZippyApp());
class MyZippyApp extends StatelessWidget {
final String testingText = 'Thank you Farhan Syah';
#override
Widget build(BuildContext context) {
return Provider(
create: (context) => testingText,
child: MaterialApp(
home:
TasksScreen(), // matches "TasksScreen" class created on tasks_screen.dart
),
);
}
}
Provider widget has a required create properties.
you should use 'create' to create an object which you want to provide.
return Provider(
create: (context)=> ObjectToBeProvidedHere(),
child: MaterialApp(
home:
TasksScreen(), // matches "TasksScreen" class created on tasks_screen.dart
),
);

Convert a String into Variable in Flutter - Text Widget

I want to display a text widget using dynamic values in flutter app.
Here's my code.
class _DetailsPageState extends State<DetailsPage> {
var descVar;
#override
void initState() {
var pick = widget.classDesc;
var picker = "ClassesInfo."+pick;
setState(() {
descVar = picker;
print(descVar);
});
}
...
In the build:
Text('${this.descVar}')
I wish to get value from external file:
class ClassesInfo {
static const String desc_class1 = "Sahaja Yoga";
}
I am just getting the string output, but not the value from the variable!
Desired Output : Sahaja Yoga
Getting Now: ClassesInfo.desc_class1
Even if i print the value in class it is getting : ClassesInfo.desc_class1
as i understood you want to print in text field value of desc_class const. So you can simply write:
Text(ClassesInfo.desc_class1)

Flutter. Using a builder that returns a dynamic but actually needs a Future<T>

I am trying to use the below sharedPreferenceBuilder by Simon Lightfoot.
class SharedPreferencesBuilder<T> extends StatelessWidget {
final String pref;
final AsyncWidgetBuilder<T> builder;
const SharedPreferencesBuilder({
Key key,
#required this.pref,
#required this.builder,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return FutureBuilder<T>(
future: _future(),
builder: (BuildContext context, AsyncSnapshot<T> snapshot) {
return builder(context, snapshot);
});
}
Future<T> _future() async {
return (await SharedPreferences.getInstance()).get(pref); <-------- Here is the issue
}
}
Unfortunately the _future() function is returning a dynamic type instead of a Future. I tried putting as Future<T> at the end of the return but it still did not work.
Is there any way I can convert a dynamic type into a Future?
I have also been explicit and swapped the <T> for <String> but that hasn't worked either.
Thanks for any help you can provide.

groovy design pattern for forms

I really like the groovy language but I believe my java experience is leading me to a path where I don't use groovys fully potential.
I have a scenario where a groovy object (Master.groovy) sends some json-data to some view that creates a form out of this data. Then the user can submit this form and Master.groovy receives it as json-data again.
Master.groovy can access a pool of different form descriptions (formDesc1, formDesc2, etc.) which it choses from when sending the json to the view. When the user returns the json data - Master.groovy will then pass it over to e.g. formDesc1 to validate it.
This is how it looks with code:
Master.groovy
class Master {
FormDesc[] formDescs = [new FormDesc1(), new FormDesc2(), new FormDesc2()]
def getJSONform(Integer formId){
return formDescs[formId].getForm()
}
def validateForm(Integer formId, def data) {
return formDescs[formId].validate(data)
}
}
FormDesc1.groovy
class FormDesc1 extends FormDesc {
static String name = "alias"
FormDesc1 (){
form.add(new InputElement(name:name, type:"text"))
form.add(new TextArea(name:"msg", rows:"12", cols:"12"))
}
#Override
def validate(data){
errors = []
if(data.get(name)["value"] != "form1")
errors.add("name not allowed")
return errors
}
}
FormDesc2.groovy
class FormDesc2 extends FormDesc {
static String name = "alias"
FormDesc1 (){
form.add(new InputElement(name:name, type:"text"))
form.add(new TextArea(name:"msg", rows:"12", cols:"12"))
}
#Override
def validate(data){
errors = []
if(data.get(name)["value"] != "form1")
errors.add("name not allowed")
return errors
}
}
There can be many forms in the package /forms and to load all of them in the memory seems very unnecessary. And it would be much nicer if the formDesc consisted of json-data that represented the form and then only has the method validate. E.g:
FormDescUltimate.groovy
class FormDescUltimate extends FormDesc {
form = loadJSONFile("formDescUltimate.json")
#Override
def validate(data){
errors = []
if(data.get("alias")["value"] != "form1")
errors.add("name not allowed")
return errors
}
}
formDescUltimate.json
{
'formId' : 'ultimate_form',
'elements': [
{'InputElement' : {'name': 'alias', 'type':'text'}},
{'TextArea' : {'name': 'msg', 'rows':'12', 'cols':'12'}}
]
}
Is it possible to achieve this nicely with groovy, or is there any better design to accomplish this?
Thanks in advance and sorry for the long post!

Resources