The getter 'activePageIndex' was called on null. Receiver: null Tried calling: activePageIndex) - flutter

while creating a liquid swipe with smooth page indicator I am getting an error
the error which I getting is
NoSuchMethodError (NoSuchMethodError: The getter 'activePageIndex' was called on null. Receiver: nullTried calling: activePageIndex)
Please anyone can help me to get rid of this error
My Code
import 'package:flutter/material.dart';
import 'package:liquid_swipe/liquid_swipe.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
void main(List<String> args) {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SwipeHome(),
);
}
}
class SwipeHome extends StatefulWidget {
#override
State<SwipeHome> createState() => _SwipeHomeState();
}
class _SwipeHomeState extends State<SwipeHome> {
final controller= LiquidController();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children :[
LiquidSwipe(
liquidController: controller,
enableSlideIcon: true,
onPageChangeCallback: (index){
setState(() {
});
},
slideIconWidget: Icon(Icons.arrow_back_ios_new,color: Colors.white,),
pages:[
BuildPage(color: Color.fromARGB(255, 27, 4, 119),
urlImage: "https://i.pcmag.com/imagery/articles/04HUXgEu0I3mdCOejOjQpNE-5.fit_lim.size_1600x900.v1620748900.jpg",
title: "Facebook",
subtitle: "nfvfhgsdcfyfshsiufifuihgiugerbdfyfu"),
BuildPage(color: Colors.white,
urlImage: "https://images.unsplash.com/photo-1636751364472-12bfad09b451?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80",
title: "Whatsapp",
subtitle: "nfvfhgsdcfyfshsiufifuihgiugerbdfyfu"),
BuildPage(color: Colors.orange,
urlImage: "https://akm-img-a-in.tosshub.com/indiatoday/images/story/202108/Instagram_0.jpg?ZZLGdE1PjohTO.aeUOUEQYBxAWLPgCGT&size=770:433",
title: "Instagram",
subtitle: "nfvfhgsdcfyfshsiufifuihgiugerbdfyfu")
]),
Positioned(
bottom: 0,
left: 16,
right: 32,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(onPressed: (){
controller.animateToPage(page: 2);
}, child: Text("Skip",style: TextStyle(color: Colors.white,fontSize: 15),)),
AnimatedSmoothIndicator(activeIndex:controller.currentPage,//THIS IS WHERE I AM GETTING ERROR//
count: 3,
effect: JumpingDotEffect(),
onDotClicked: (index){
controller.animateToPage(page: index);
},
),
TextButton(onPressed: (){
final page = controller.currentPage+1;
controller.animateToPage(page: page>3?0:page,duration: 300);
}, child: Text("Next",style: TextStyle(color: Colors.white,fontSize: 15),)),
],
))
]
)
);
}
Widget BuildPage({required Color color,
required String urlImage,
required String title,
required String subtitle,
}){
return Container(
color: color,
padding: EdgeInsets.symmetric(horizontal: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.network(urlImage,fit: BoxFit.cover,
width: double.infinity,),
SizedBox(height: 64),
Center(child: Text(title,style: TextStyle(color: Colors.white,fontSize: 28,fontWeight: FontWeight.bold),)),
SizedBox(height: 24),
Container(
child: Text(subtitle,style:TextStyle(color: Colors.white,fontSize: 20,)),
)
],
),
);
}
}
*Plz anyone can help me to get rid of this error

Related

How do I fix my problem with routes in Flutter?

good evening. I am currently doing a To-do List in Flutter and I want to pass the Title of my List and the Description of my List when I click on a new screen but upon setting up Routes and and declaring the values on my next, it shows the "2 positional arguments expected, but 0 found" on the routes I've set up. Here are my codes:
Here is my 1st screen:
import 'package:flutter/material.dart';
import 'package:todo_list/details.dart';
import 'package:todo_list/note.dart';
class MyApp extends StatelessWidget {
final String text;
final int number;
final String listDescription;
const MyApp(
{super.key,
required this.text,
required this.number,
required this.listDescription});
#override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
DetailsPage.routeName: (ctx) => DetailsPage(),
},
home: CustomListTile(
text: text,
number: number,
listDescription: listDescription,
),
);
}
}
class CustomListTile extends StatelessWidget {
final String text;
final int number;
final String listDescription;
const CustomListTile(
{super.key,
required this.text,
required this.number,
required this.listDescription});
#override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
Navigator.pushNamed(context, DetailsPage.routeName,
arguments: Note(title: text, description: listDescription));
},
/* onTap: () {
Widget okButton = TextButton(
child: const Text("CLOSE"),
onPressed: () {
Navigator.of(context).pop();
},
);
AlertDialog alert = AlertDialog(
title: Text(text),
content: Text('This item in the list contains $listDescription'),
actions: [
okButton,
]);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
});
}, */
child: Padding(
padding: const EdgeInsets.only(left: 20.0, right: 20.0, top: 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("$number. $text",
style: const TextStyle(
fontSize: 20,
)),
const Icon(Icons.chevron_right)
],
),
Text(
listDescription,
style: const TextStyle(fontSize: 14, color: Colors.grey),
),
const Divider()
],
),
),
);
}
}
and here is my 2nd screen:
import 'package:flutter/material.dart';
import 'note.dart';
class DetailsPage extends StatefulWidget {
static const String routeName = "/details";
final String text;
final String listDescription;
const DetailsPage(this.text, this.listDescription, {super.key});
#override
State<DetailsPage> createState() => _DetailsPageState();
}
class _DetailsPageState extends State<DetailsPage> {
late Note params;
#override
void didChangeDependencies() {
params = ModalRoute.of(context)!.settings.arguments! as Note;
super.didChangeDependencies();
}
#override
Widget build(BuildContext context) {
Widget titleSection = Container(
padding: const EdgeInsets.all(32),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.only(bottom: 0),
child: Text(
params.title,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
),
),
),
],
),
),
],
),
);
Color color = Theme.of(context).primaryColor;
Widget buttonSection = Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildButtonColumn(
color,
Icons.edit,
'EDIT',
),
_buildButtonColumn(color, Icons.delete, 'DELETE'),
],
);
Widget textSection = Padding(
padding: const EdgeInsets.all(20),
child: Text(
params.description,
softWrap: true,
),
);
return MaterialApp(
title: 'Layout for a New Screen',
theme: ThemeData(
primarySwatch: Colors.brown,
),
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
},
),
title: Text(params.title),
),
body: ListView(
children: [
Image.asset(
'lib/images/placeholder.jpg',
width: 600,
height: 240,
fit: BoxFit.cover,
),
titleSection,
buttonSection,
textSection,
],
),
),
);
}
Column _buildButtonColumn(
Color color,
IconData icon,
String label,
) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, color: color),
Container(
margin: const EdgeInsets.only(top: 8),
child: Text(
label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
color: color,
),
),
),
],
);
}
}
/* return Scaffold(
appBar: AppBar(title: Text(text)),
body: Center(
child: Row(
children: [Text(description)],
),
));
}
} */
How do I make it so that the data I'll pass such as the Title and the Description will appear on the 2nd screen without the error "2 positional argument(s) expected, but 0 found.
Try adding the missing arguments." appearing.
I tried the Quick Fixes on VS Code such as adding a const modifier but I think the const modifier wouldn't do a fix since both data I'm trying to pass are dynamic and may change from time to time.
As you've define details page
class DetailsPage extends StatefulWidget {
static const String routeName = "/details";
final String text;
final String listDescription;
const DetailsPage(this.text, this.listDescription, {super.key});
You need to pass two string as positional argument.
So it can be
routes: {
DetailsPage.routeName: (ctx) => DetailsPage("text","description"),
},
also while you are using route arguments, you can remove theses from widget class and just accept from state class context with ModalRoute.
You can check this example and development/ui/navigation .

how to add two posts per screen flutter

I'm trying to create a video screen like the picture. on the right side picture showing my implementation so far. how can I create video screen like half of the screen and one after the other as left UI below. (two videos per screen). appriciate your help on this. I haveadded my code for your refernce
post_template.dart
import 'package:flutter/material.dart';
import '../constants/button.dart';
class PostTemplate extends StatelessWidget {
final String username;
final String videoDescription;
final String numberOfLikes;
final String numberOfComments;
final String numberOfShares;
final userPost;
PostTemplate({
required this.username,
required this.videoDescription,
required this.numberOfLikes,
required this.numberOfComments,
required this.numberOfShares,
required this.userPost,
});
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
// user post (at the very back)
userPost,
// user name and caption
Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
alignment: Alignment(-1, 1),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text('#' + username,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
)),
SizedBox(
height: 10,
),
RichText(
text: TextSpan(
children: [
TextSpan(
text: videoDescription,
style: TextStyle(color: Colors.white)),
TextSpan(
text: ' #live #lalaive',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white)),
],
),
)
],
),
),
),
// buttons
Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
alignment: Alignment(1, 1),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
MyButton(
icon: Icons.people,
number: numberOfComments,
),
MyButton(
icon: Icons.thumb_up,
number: numberOfLikes,
),
MyButton(
icon: Icons.share,
number: numberOfShares,
),
],
),
),
)
],
),
);
}
}
video_screen.dart
import 'package:flutter/material.dart';
import 'package:lala_live/screens/post_template.dart';
class VideoScreen extends StatefulWidget {
const VideoScreen({Key? key}) : super(key: key);
#override
_VideoScreenState createState() => _VideoScreenState();
}
class _VideoScreenState extends State<VideoScreen> {
final _controller = PageController(initialPage: 0);
#override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
controller: _controller,
scrollDirection: Axis.vertical,
children: [
MyPost1(),
MyPost2(),
MyPost3(),
],
),
);
}
}
class MyPost1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return PostTemplate(
username: 'amandasharma',
videoDescription: 'Free your mind',
numberOfLikes: '1.2M',
numberOfComments: '1232',
numberOfShares: '122',
userPost: Container(
//color: Colors.deepPurple[300],
decoration: new BoxDecoration(
image: new DecorationImage(
image: new AssetImage("asset/images/girl.jpeg"),
fit: BoxFit.fill,
)
)
)
);
}
}
class MyPost2 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return PostTemplate(
username: 'zuckerberg',
videoDescription: 'reels for days',
numberOfLikes: '1.2M',
numberOfComments: '232',
numberOfShares: '122',
userPost: Container(
decoration: new BoxDecoration(
image: new DecorationImage(
image: new AssetImage("asset/images/nature.jpg"),
fit: BoxFit.fill,
)
)
),
);
}
}
class MyPost3 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return PostTemplate(
username: 'randomUser',
videoDescription: 'Free your mind',
numberOfLikes: '1.2B',
numberOfComments: '232',
numberOfShares: '122',
userPost: Container(
color: Colors.blue[300],
),
);
}
}
for MyPost3() you can wrap the containers in a column and use the Expanded widget.
class MyPost3 extends StatelessWidget {
const MyPost3({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return PostTemplate(
username: 'randomUser',
videoDescription: 'Free your mind',
numberOfLikes: '1.2B',
numberOfComments: '232',
numberOfShares: '122',
userPost: Column(
children: [
Expanded(
child: Container(
color: Colors.blue[300],
),
),
Expanded(
child: Container(
color: Colors.red[300],
),
),
],
),
);
}
}
I believe this is where you want the video widgets to appear ,
// user post (at the very back)
userPost,
You can put the widgets in a column and use Expandable to give them size, i.e flex 2 for each to split screen halfway.
Column -
- Expanded( flex:2, child:video1
- Expanded( flex:2, child:video2
On MyPost3():
return PostTemplate(
username: 'randomUser',
videoDescription: 'Free your mind',
numberOfLikes: '1.2B',
numberOfComments: '232',
numberOfShares: '122',
userPost: SafeArea(
child: Column(children: [
Expanded(
child: Container(
color: Colors.blue,
)),
Expanded(
child: Container(
color: Colors.red,
))
]),
));
You can use an Expanded() to take as much space you can, surrounded by a SafeArea() to ensure your screens don't overlap with your status bar leaving the possibility of an overflow.

create field for load images

I have a code that outputs fields for the user to fill in (code below. I have shortened it here for ease of reading.). I would like to add one more field to this form, which can upload various photos from the phone gallery (preferably with the ability to delete a photo if the user made a mistake when choosing). How can I implement this?
class FormForDeviceService extends StatefulWidget {
#override
State<StatefulWidget> createState() => _FormForDeviceService();
}
class _FormForDeviceService extends State {
final _formKey = GlobalKey<FormState>();
Widget build(BuildContext context) {
return Container(padding: const EdgeInsets.all(10.0),
child: Form(key: _formKey, child: Column(children: <Widget>[
new Text('What is problem', style: TextStyle(fontSize: 20.0),),
new TextFormField(decoration: const InputDecoration(
hintText: 'Describe the problem',),
ElevatedButton(
onPressed: (){if(_formKey.currentState!.validate()) {_formKey.currentState?.reset();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Form completed successfully', style: TextStyle(color: Colors.black),),
backgroundColor: Colors.yellow,));
}},
child: const Text('Submit', style: TextStyle(color: Colors.black),),
style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.yellow)),)
],)));
}
}
Page at the moment
my expectations (or something similar)
An another approach is here-
(I have made a separate widget to handle all these things and you just need to attach it in any scrollable widget)
my code is as follow:
Main Code with that custom widget:
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_memory/image_picker_widget.dart';
void main() {
runApp(GetMaterialApp(title: 'Flutter', home: Flutter()));
}
class Flutter extends StatefulWidget {
const Flutter({Key? key}) : super(key: key);
#override
State<Flutter> createState() => _FlutterState();
}
class _FlutterState extends State<Flutter> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter'),
centerTitle: true,
),
body: Center(
child: Column(
children: [
//This is the widget I am talking about
ImagePickerWidget()
],
),
),
);
}
}
And now the code for that custom widget:
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class ImagePickerWidget extends StatefulWidget {
const ImagePickerWidget({Key? key}) : super(key: key);
#override
State<ImagePickerWidget> createState() => _ImagePickerWidgetState();
}
class _ImagePickerWidgetState extends State<ImagePickerWidget> {
late List<CustomImage> images;
late double size;
late ImagePicker imagePicker;
late int idGenerator;
#override
void initState() {
images = [];
size = 100;
idGenerator = 0;
imagePicker = ImagePicker();
}
#override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
pickImage();
},
child: Text('Pick Image')),
Wrap(
children: images.map((image) {
return Stack(children: [
SizedBox(
height: size,
width: size,
child: ClipRRect(
child: Image.memory(
image.imageData,
fit: BoxFit.fill,
))),
Positioned(
right: 4,
top: 4,
child: InkWell(
onTap: () {
//delete image
images.removeWhere(
(element) => element.imageData == image.imageData);
setState(() {});
},
child: Container(
color: Colors.white, child: Icon(Icons.clear))))
]);
}).toList())
],
);
}
Future<void> pickImage() async {
// XFile? image = await imagePicker.pickImage(source: ImageSource.camera);
XFile? image = await imagePicker.pickImage(source: ImageSource.gallery);
if (image != null) {
Uint8List imageData = await image.readAsBytes();
int id = idGenerator++;
images.add(CustomImage(imageData: imageData, id: id));
setState(() {});
}
}
}
class CustomImage {
Uint8List imageData;
int id;
CustomImage({required this.imageData, required this.id});
}
You can customize the widget in order to use the images list of that widget or you can simply pass the callbacks for that.
we store file here your can use path(string) instead file
List<File> myfile = [];
image_picker package used here to pick image
image_picker: ^0.8.4+10
call like this in your code
Container(
height: 200,
padding: EdgeInsets.all(4),
child: PickPhoto())
Pick photo widget
class PickPhoto extends StatefulWidget {
const PickPhoto({Key? key}) : super(key: key);
#override
State<PickPhoto> createState() => _PickPhotoState();
}
class _PickPhotoState extends State<PickPhoto> {
#override
Widget build(BuildContext context) {
return Material(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Container(
width: 45,
height: 45,
child: ElevatedButton(
onPressed: () async {
var file =
await picker?.pickImage(source: ImageSource.gallery);
setState(() {
myfile.add(File(file!.path));
});
},
child: Text("Add Photo"))),
),
Expanded(
child: ListView.builder(
// physics: NeverScrollableScrollPhysics(),
scrollDirection: Axis.horizontal,
itemCount: myfile.length,
itemBuilder: (context, index) => Container(
padding: EdgeInsets.all(4),
height: 175,
width: 125,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Align(
alignment: Alignment.topRight,
child: IconButton(
onPressed: () {
setState(() {
myfile.removeAt(index);
});
},
icon: Icon(Icons.close),
),
),
Expanded(
child: Container(
child: myfile[index] == null
? Text("")
: Image.file(
myfile[index],
fit: BoxFit.fill,
),
),
),
],
),
)),
)
],
),
);
}
}
SampleCode
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
ImagePicker? picker;
void main() {
WidgetsFlutterBinding.ensureInitialized();
picker = ImagePicker();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MySQL Test',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: [FormForDeviceService()],
),
);
}
}
List<File> myfile = [];
List<int> f = [1, 2, 3, 4, 5];
List<bool> fs = [false, false, false, true, true];
class FormForDeviceService extends StatefulWidget {
#override
State<StatefulWidget> createState() => _FormForDeviceService();
}
class _FormForDeviceService extends State {
final _formKey = GlobalKey<FormState>();
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(10.0),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
new Text(
'What is problem',
style: TextStyle(fontSize: 20.0),
),
new TextFormField(
decoration: const InputDecoration(
hintText: 'Describe the problem',
),
),
Container(
height: 200,
padding: EdgeInsets.all(4),
child: PickPhoto()),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
_formKey.currentState?.reset();
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text(
'Form completed successfully',
style: TextStyle(color: Colors.black),
),
backgroundColor: Colors.yellow,
));
}
},
child: const Text(
'Submit',
style: TextStyle(color: Colors.black),
),
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.yellow)),
)
],
)));
}
}
class PickPhoto extends StatefulWidget {
const PickPhoto({Key? key}) : super(key: key);
#override
State<PickPhoto> createState() => _PickPhotoState();
}
class _PickPhotoState extends State<PickPhoto> {
#override
Widget build(BuildContext context) {
return Material(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Container(
width: 45,
height: 45,
child: ElevatedButton(
onPressed: () async {
var file =
await picker?.pickImage(source: ImageSource.gallery);
setState(() {
myfile.add(File(file!.path));
});
},
child: Text("Add Photo"))),
),
Expanded(
child: ListView.builder(
// physics: NeverScrollableScrollPhysics(),
scrollDirection: Axis.horizontal,
itemCount: myfile.length,
itemBuilder: (context, index) => Container(
padding: EdgeInsets.all(4),
height: 175,
width: 125,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Align(
alignment: Alignment.topRight,
child: IconButton(
onPressed: () {
setState(() {
myfile.removeAt(index);
});
},
icon: Icon(Icons.close),
),
),
Expanded(
child: Container(
child: myfile[index] == null
? Text("")
: Image.file(
myfile[index],
fit: BoxFit.fill,
),
),
),
],
),
)),
)
],
),
);
}
}

Why can I not assign type 'Translation' to type 'String' using translator plugin?

I am building a translation app and am having difficulties with assigning the final translation to a variable storing that translation, because I want to use it in another place. Code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:translator/translator.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Translator',
home: MyHomePage(title: 'Translator'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController textController = TextEditingController();
var translatedPhrase = "";
var translator = GoogleTranslator();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold (
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.green[100],
title: const Text(
"What Are You Saying In Spanish?",
style: TextStyle(
fontSize: 20.0,
color: Colors.black,
fontWeight: FontWeight.w600,
),
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Flexible(
flex: 1,
child: Container(
width: double.infinity,
height: double.infinity,
color: Colors.lightBlue,
child: Column(
children: <Widget>[
TextField(
controller: textController,
),
MaterialButton(
child: const Text("Translate"),
color: Colors.white,
onPressed: () {
setState(() {
// ignore: non_constant_identifier_names
translator.translate(textController.text, from: "en", to: "es").then((t) {
setState(() {
translatedPhrase = t;
});
});
});
},
),
],
),
),
),
Flexible(
flex: 1,
child: Container(
width: double.infinity,
height: double.infinity,
color: Colors.grey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
translatedPhrase,
style: const TextStyle(
fontSize: 20,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget> [
MaterialButton(
child: const Icon(Icons.clear),
onPressed: () {
setState(() {
translatedPhrase = "";
textController.text = "";
});
},
),
MaterialButton(
child: const Icon(Icons.content_copy),
onPressed: () {
Clipboard.setData(ClipboardData(text: translatedPhrase));
},
),
],
)
],
),
),
),
],
),
),
),
);
}
}
I am getting the error "A value of type 'Translation' can't be assigned to a variable of type 'String'. Try changing the type of the variable, or casting the right-hand type to 'String'." on line 77 (translatedPhrase = t;). basically, I just would like some help/advice on how to get the Materialbutton working to do the translation function. Thank you!
The translate method returns a Translation Object so You can not assign it to a String. The Translation object has a property text.
So your code should look like this:
translator.translate(textController.text, from: "en", to: "es").then((t) {
setState(() {
translatedPhrase = t.text;
});
});
Try with the following code, hope you got the solution.
GoogleTranslator translator = GoogleTranslator();
await translator
.translate(textController.text, from: 'en', to: 'es')
.then((value) {
translatedPhrase = value.toString();
setState(() {});
});

Flutter StatefulWidget parameter unable to pass

I know there was a really similar case and got solved, I modified my code to 99% liked to that but somehow my list is undefined.
The list that is undefined is at the line where ' ...(list as List).map((answer) { '.
import 'package:flutter/material.dart';
import 'package:kzstats/common/AppBar.dart';
import 'package:kzstats/common/Drawer.dart';
import '../toggleButton.dart';
class Settings extends StatelessWidget {
final String currentPage = 'Settings';
static const _modes = [
{
'mode': ['KZTimer', 'SimpleKZ', 'Vanilla']
},
{
'tickrate': [128, 102, 64]
},
];
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: HomepageAppBar(currentPage),
drawer: HomepageDrawer(),
body: Padding(
padding: EdgeInsets.all(8),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildHeader(
title: 'Mode',
child: ToggleButton(_modes[0]['mode']),
),
SizedBox(height: 32),
buildHeader(
title: 'Tick rate',
child: ToggleButton(_modes[1]['tickrate']),
),
],
),
),
),
),
);
}
}
Widget buildHeader({#required String title, #required Widget child}) => Column(
children: [
Text(
title,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
const SizedBox(height: 16),
child,
],
);
class ToggleButton extends StatefulWidget {
final List<String> list;
ToggleButton(this.list);
#override
State createState() => new _ToggleButtonState();
}
class _ToggleButtonState extends State<ToggleButton> {
List<bool> _selections = [true, false, false];
#override
Widget build(BuildContext context) {
return new Container(
color: Colors.blue.shade200,
child: ToggleButtons(
isSelected: _selections,
fillColor: Colors.lightBlue,
color: Colors.black,
selectedColor: Colors.white,
renderBorder: false,
children: <Widget>[
...(list as List<String>).map((answer) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 12),
child: Text(
answer,
style: TextStyle(fontSize: 18),
),
);
}).toList(),
],
onPressed: (int index) {
setState(() {
for (int i = 0; i < _selections.length; i++) {
if (index == i) {
_selections[i] = true;
} else {
_selections[i] = false;
}
}
});
},
),
);
}
}
In case someone needs the full code, it's available at https://github.com/davidp918/KZStats
I'm new to Flutter and stackoverflow so if anything please just comment, thanks!
We can access a variable of StatefulWidget from the state class using "widget" (for example: widget.list)
Please refer below code sample for the reference.
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(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Settings());
}
}
class Settings extends StatelessWidget {
final String currentPage = 'Settings';
static const modes = [
{
'mode': ['KZTimer', 'SimpleKZ', 'Vanilla']
},
{
'tickrate': [128, 102, 64]
},
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Container(
child: Padding(
padding: EdgeInsets.all(8),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildHeader(
title: 'Mode',
child: ToggleButton(modes[0]['mode']),
),
SizedBox(height: 32),
buildHeader(
title: 'Tick rate',
child: ToggleButton(modes[1]['tickrate']),
),
SizedBox(height: 32),
buildHeader(
title: 'Mode',
child: ToggleButton(modes[0]['mode']),
),
],
),
),
),
),
),
);
}
}
Widget buildHeader({#required String title, #required Widget child}) {
return Column(
children: [
Text(
title,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
SizedBox(height: 16),
child,
],
);
}
class ToggleButton extends StatefulWidget {
final List list;
ToggleButton(this.list);
#override
State createState() => new _ToggleButtonState();
}
class _ToggleButtonState extends State<ToggleButton> {
List<bool> _selections = [false, false, false];
#override
Widget build(BuildContext context) {
return Container(
color: Colors.blue.shade200,
child: ToggleButtons(
isSelected: _selections,
fillColor: Colors.lightBlue,
color: Colors.black,
selectedColor: Colors.white,
renderBorder: false,
children: [
...(widget.list as List)?.map((answer) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 12),
child: Text(
answer.toString() ?? '',
style: TextStyle(fontSize: 18),
),
);
})?.toList(),
],
onPressed: (int index) {
setState(() {
for (int i = 0; i < _selections.length; i++) {
if (index == i) {
_selections[i] = true;
} else {
_selections[i] = false;
}
}
});
},
),
);
}
}