The named parameter 'textColor' isn't defined - flutter

I'm getting this error when writing for example color or textColor maybe even with more.
I tried:
flutter clean -> everything is now red, even after restarting. I have to use
'flutter pub get' to get it back to normal
restating PC
ctrl + shift + p -> Dart: Restart Analysis Server
Nothing changes
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final VoidCallback selectHandler;
Answer(this.selectHandler);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
textColor: Colors.green,
child: Text('Answer 1'),
onPressed: selectHandler,
),
);
}
}
I have no idea what to do and I'm starting to hate this language more and more
Some help would really be appreciated

Do this:
class Answer extends StatelessWidget {
final VoidCallback selectHandler;
Answer(this.selectHandler);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
child: Text('Answer 1', style: TextStyle(color: Colors.green)),
onPressed: selectHandler,
),
);
}
}

Related

How can I Remove an error While Defining return type as VoidCallback of a property?

I get an error Whenever I try to use VoidCallback instead of function when i Define GetAnswer.I am using it as a pointer to get value in it in the constructor below.But I am continuously getting an error shown in the 2nd pic.Seniors Plz Guide
import 'dart:html';
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final VoidCallback GetAnswer;
Answer(this.GetAnswer);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: RaisedButton(
color: Colors.blue,
child: Text("4 CGPA"),
onPressed: GetAnswer,
),
);
}
}
Remove the import import 'dart:html';
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final VoidCallback GetAnswer;
Answer(this.GetAnswer);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: RaisedButton(
color: Colors.blue,
child: Text("4 CGPA"),
onPressed: GetAnswer,
),
);
}
}

How to click the button in flutter to change the background image

I am a beginner in flutter, I don’t understand the concept of Widget very well.
I want to set the background image as an unsplash random image, but I want to add a button to request a random image again when I click it, but I am confused about many concepts of Flutter, and I don’t know how to complete this function.
Below is my current code, I don’t know how to change it, please help me, thank you very much!
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: 'Welcome to Flutter',
theme: new ThemeData(
brightness: Brightness.light,
),
home: new Scaffold(
appBar: new AppBar(
title: new Text("Welcome to Flutter"),
),
body: BackgroundImgDemo()
),
);
}
}
class BackgroundImgDemo extends StatelessWidget {
final String imgUrl="https://unsplash.it/1440/3040?random";
const BackgroundImgDemo({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
image: new DecorationImage(
fit: BoxFit.cover,
image: new NetworkImage(imgUrl),
),
),
child: Container(
margin: EdgeInsets.only(top: 500.0),
child: Center(
child: RaisedButton(
color: Colors.white,
child: Text("clicke here!"),
onPressed: () {
},
)
),
),
);
}
}
I'm also a very beginner and I attempted to solve your problem.
My approach was to
change your stateless widget to stateful widget
Used a NetworkImage variable showImg to pass to the image widget
create a function updateUI that will refresh the image to show
called updateUI from onPressed function
But this doesn't seem to be working as well. Following the thread to know how to do it
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: 'Welcome to Flutter',
theme: new ThemeData(
brightness: Brightness.light,
),
home: new Scaffold(
appBar: new AppBar(
title: new Text("Welcome to Flutter"),
),
body: BackgroundImgDemo()),
);
}
}
class BackgroundImgDemo extends StatefulWidget {
#override
State<BackgroundImgDemo> createState() => _BackgroundImgDemoState();
}
class _BackgroundImgDemoState extends State<BackgroundImgDemo> {
final String imgUrl = "https://unsplash.it/1440/3040?random";
NetworkImage showImg = NetworkImage("https://unsplash.it/1440/3040?random");
void updateUI() {
setState(() {
showImg = NetworkImage(imgUrl);
});
}
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: showImg,
),
),
child: Container(
margin: EdgeInsets.only(top: 500.0),
child: Center(
child: RaisedButton(
color: Colors.white,
child: const Text("click here!"),
onPressed: () => updateUI(),
),
),
),
);
}
}
Firstly, you need to use StatefulWidget to make any changes over UI. But here the second issue is image is loading from cache after 1st load being the same URL.
As long you use the same URL within context, images will load from cache.
about the upspash URL you can tweak some value by adding something at the end of URL on button pressed.
Here is the widget
class MyWidgetsBinding extends WidgetsFlutterBinding {
#override
ImageCache createImageCache() => MyImageCache();
}
class _BackgroundImgDemoState extends State<BackgroundImgDemo> {
String imgUrl1 = "https://unsplash.it/1440/3040?random";
int count = 0;
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
image: new DecorationImage(
fit: BoxFit.cover,
image: new NetworkImage(
"${imgUrl1}$count",
),
),
),
child: Container(
margin: EdgeInsets.only(top: 500.0),
child: Center(
child: RaisedButton(
color: Colors.white,
child: Text("clicke here!"),
onPressed: () async {
print("clear cache");
setState(() {
count++;
});
},
)),
),
);
}
}
You can also try cached_network_image to maintain cache.
The solution is simple since the URL never changes flutter assumes that the image is the same and loads it from the cache. To get around this problem all you have to do is provide a different URL every time you click the button. To do this you have to pass a random value to the URL.
"https://unsplash.it/1440/3040?random" + "#v=${DateTime.now().microsecondsSinceEpoch}"
Everything after a # is ignored so it doesn't matter what random value you add but it lets the builder know the URL is changed. You can pass this URL inside a setState to rebuild with the new URL. With this method, you won't have to create any function at all.
class BackgroundImgDemo
class BackgroundImgDemo extends StatefulWidget {
const BackgroundImgDemo({Key? key}) : super(key: key);
#override
_BackgroundImgDemoState createState() => _BackgroundImgDemoState();
}
class _BackgroundImgDemoState extends State<BackgroundImgDemo> {
String imgUrl = "https://unsplash.it/1440/3040?random";
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(imgUrl),
),
),
child: Container(
margin: const EdgeInsets.only(top: 500.0),
child: Center(
child: ElevatedButton(
onPressed: () {
setState(() {
imgUrl = "https://unsplash.it/1440/3040?random"
"#v=${DateTime.now().microsecondsSinceEpoch}";
});
},
child: const Text('Click Here!')),
),
),
),
);
}
}

I want my onPressed method to open the keyboard of Spinbox

I use spinbox to set the number of break time in minutes. If you tap on the number a keyboard opens, and you can set your number. How do I open the Same keyboard of my spinbox, while pressing on the ElevatedButton?
I prepared the code for testing below,
and I added (flutter_spinbox: ^0.4.0) to pubspec.yaml
import 'package:flutter/material.dart';
import 'package:flutter_spinbox/flutter_spinbox.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
int breaktime = 60;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("SpinBox")),
body: Column(
children: [
Container(
child: ElevatedButton(
child: Text(
'Break in minutes',
),
onPressed: () => {},
),
),
Container(
height: 35,
child: SpinBox(
min: 0,
max: 120,
value: 60,
onChanged: (value) => breaktime = value.toInt(),
),
),
],
),
),
);
}
}
Unfortunately, based on SpinBox sources, there's no easy way to do it.
Thankfully, there's a workaround:
class MyApp extends StatelessWidget {
final spinBoxKey = GlobalKey();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SpinBox(
key: spinBoxKey,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
final focusNode = (spinBoxKey.currentState as dynamic).focusNode as FocusNode;
focusNode.requestFocus();
},
child: Icon(Icons.keyboard),
),
),
);
}
}
assign a GlobalKey to the widget (SpinBox in this case)
onClick:
extract BaseSpinBoxState state using key that you've created before
BaseSpinBoxState has focusNode getter, call it and invoke requestFocus on it

how to get a grid element accessible in flutter by clicking on it?

is there anyone who can help me ?
I am currently on a project where i want to visualize pathfinding-algorithms by using flutter (i want to use it as app later on).
My Problem:
I have a gridPaper and it's perfectly formatted for my needs... but how can i make the single elements in it accessible by clicking on them ?
I want to create a 'wall' between the start- and endnode to make it harder for the pathfinding-algorithm. (if that makes sense)
But at first i need to create a start- end endnode as well.
Here is what i have so far:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final appTitle = 'Path Finder';
final Color gridColor = Colors.lightBlue[100];
#override
Widget build(BuildContext context) {
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: GridPaper(
child: Container(),
color: Colors.lightBlue[100],
interval: 20,
divisions: 1,
subdivisions: 1,
),
drawer: Drawer(
// Add a ListView to the drawer. This ensures the user can scroll
// through the options in the drawer if there isn't enough vertical
// space to fit everything.
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Text('Drawer Header'),
decoration: BoxDecoration(
color: Colors.blue,
),
),
ListTile(
title: Text('Startpunkt'),
onTap: () {
// Update the state of the app
// ...
// Then close the drawer
Navigator.pop(context);
},
),
ListTile(
title: Text('Ziel'),
onTap: () {
// Update the state of the app
// ...
// Then close the drawer
Navigator.pop(context);
},
),
],
),
),
);
}
}
LG Robsen
Since your GridPaper is defined with intervals of 20, it will be quite easy to use the localPosition of the details of an onTapDown callback provided by a GestureDetector on the whole GridPaper:
Full source code
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final appTitle = 'Path Finder';
final Color gridColor = Colors.lightBlue[100];
#override
Widget build(BuildContext context) {
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends HookWidget {
final double cellSize = 20.0;
final String title;
MyHomePage({
Key key,
this.title,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final _activated = useState<List<Offset>>([]);
void _toggle(Offset offset) {
if (!_activated.value.remove(offset)) _activated.value.add(offset);
_activated.value = [..._activated.value];
}
return Scaffold(
appBar: AppBar(title: Text(title)),
body: GestureDetector(
onTapDown: (details) => _toggle(details.localPosition ~/ cellSize),
child: GridPaper(
child: Stack(
children: [
Container(color: Colors.white),
..._activated.value.map((offset) {
print('OFFSET: $offset');
return Positioned(
left: offset.dx * cellSize,
top: offset.dy * cellSize,
width: cellSize,
height: cellSize,
child: ColoredBox(color: Colors.green.shade200),
);
}).toList(),
],
),
color: Colors.lightBlue[100],
interval: cellSize,
divisions: 1,
subdivisions: 1,
),
),
drawer: Drawer(
// Add a ListView to the drawer. This ensures the user can scroll
// through the options in the drawer if there isn't enough vertical
// space to fit everything.
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Text('Drawer Header'),
decoration: BoxDecoration(
color: Colors.blue,
),
),
ListTile(
title: Text('Startpunkt'),
onTap: () {
// Update the state of the app
// ...
// Then close the drawer
Navigator.pop(context);
},
),
ListTile(
title: Text('Ziel'),
onTap: () {
// Update the state of the app
// ...
// Then close the drawer
Navigator.pop(context);
},
),
],
),
),
);
}
}

flutter's AutomaticKeepAliveClientMixin doesn't keep the page state after navigator.push

was testing AutomaticKeepAliveClientMixin and run into an issue,
page loses state after navigator.push
anyone knows this issue? any workarounds? be glad for any info, cheers
my goal is to keep the page state
steps to reproduce: open app click PageOne's push-button then go back swipe right and left and the page loses state
image
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: MyApp()));
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
initialIndex: 0,
length: 2,
child: Scaffold(
body: TabBarView(
children: <Widget>[Page1(), Page2()],
),
bottomNavigationBar: Material(
child: TabBar(
labelColor: Colors.black,
tabs: <Widget>[
Tab(
icon: Icon(Icons.check),
),
Tab(
icon: Icon(Icons.check),
),
],
),
),
),
),
);
}
}
class Page1 extends StatefulWidget {
#override
Page1State createState() {
return new Page1State();
}
}
class Page1State extends State<Page1> with AutomaticKeepAliveClientMixin {
#override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
Container(
height: 300,
color: Colors.orange,
),
Container(
height: 300,
color: Colors.pink,
),
Container(
height: 300,
color: Colors.yellow,
child: Center(
child: Container(height: 26,
child: MaterialButton(
color: Colors.blue,
child:
Text('clicking this and back then swipe => page loses state'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => PushedPage()),
);
}),
),
),
),
],
);
}
#override
bool get wantKeepAlive => true;
}
class Page2 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(height: 300, color: Colors.orange);
}
}
class PushedPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
color: Colors.blue,
),
);
}
}
From the documentation on AutomaticKeepAliveClientMixin:
A mixin with convenience methods for clients of
[AutomaticKeepAlive]. Used with [State] subclasses.
Subclasses must implement [wantKeepAlive], and their [build]
methods must call super.build (the return value will always return
null, and should be ignored).
So in your code, before you return the ListView just call super.build:
Widget build(BuildContext context) {
super.build(context);
return ListView(...
}