I am new to flutter. I tried to write my first code but got stuck. It says too to change the positional parameter to named parameter but agian it says named parameter already used. Can anyone please help me?
import 'package:flutter/material.dart';
void main() {
runApp( MaterialApp(
debugShowCheckedModeBanner: false,
title: "My app",
home: Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text("My first App")
),
body: Column(
children: [
Center(child: Image.network("https://images.unsplash.com/photo-1526779259212-
939e64788e3c?ixlib=rb-
1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1474&q=80",
height:300, width: 300,),
const Text('My first app',)
)
],
),
),
)
);
}
The URL is not correct, as the line breaks. And to your error, the Center widget has two children, which is impossible. Thus you had that error. Kindly move the Text Widget out of Center Widget to the Column Widget's children. I also tweaked a bit of your Image.network Widget, to increase the intuitiveness.
void main() {
runApp( MaterialApp(
debugShowCheckedModeBanner: false,
title: "My app",
home: Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text("My first App")
),
body: Column(
children: [
Center(
child: SizedBox(
height: 300,
width: 300,
child: Image.network("https://images.unsplash.com/photo-1526779259212-939e64788e3c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1474&q=80",
loadingBuilder: (context, child, loadingProgress) {
if(loadingProgress == null) return child;
return const Center(child: CircularProgressIndicator(),);
},height:300, width: 300),
),
),
const Text('My first app',)
],
),
),
));
}
You need to put url in single line
import 'package:flutter/material.dart';
void main() {
runApp( MaterialApp(
debugShowCheckedModeBanner: false,
title: "My app",
home: Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text("My first App")
),
body: Column(
children: [
Center(child: Image.network("single line url",
height:300, width: 300,),
const Text('My first app',)
)
],
),
),
)
);
}
Related
Executed program picture I need help. I want to make the button click circular instead of rectangular.
This is the flutter dart code that I've provided, I want to know what attribute I should change or insert for making my question possible.
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(MaterialApp(
title: 'Ask me anything',
home: Scaffold(
appBar: AppBar(
title: Text('Ask me anything'),
centerTitle: true,
backgroundColor: Colors.blue[700],
),
backgroundColor: Colors.blue[800],
body: MyApp(),
),
));
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int ballNumber = 1;
#override
Widget build(BuildContext context) {
return Center(
child: Expanded(
child: TextButton(
style: ButtonStyle(enableFeedback: true,shape: ),
onPressed: () => setState(() {
ballNumber = Random().nextInt(5) + 1;
}),
child: Image.asset(
'images/ball$ballNumber.png',
width: 400,
// height: 200,
),
),
));
}
}
You can either change button style, or just wrap the image with GestureDetector.
Round Button
ElevatedButton(
style: ElevatedButton.styleFrom(
shape: const CircleBorder(),
padding: const EdgeInsets.all(50),
),
onPressed: () {},
child: const FittedBox(
child: Text('Round Button'),
),
),
ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all<CircleBorder>(
const CircleBorder(),
),
padding: MaterialStateProperty.all<EdgeInsets>(
const EdgeInsets.all(50),
),
),
onPressed: () {},
child: const FittedBox(
child: Text('Round Button'),
),
),
GestureDetector
GestureDetector(
onTap: () {
setState(() {
ballNumber = Random().nextInt(5) + 1;
});
},
child: Image.asset('images/ball$ballNumber.png'),
),
I want to create a login screen using Flutter.
This is my code so far:
Future showInformationDialog(BuildContext context) {
TextEditingController name = TextEditingController();
TextEditingController deadline = TextEditingController();
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: SingleChildScrollView(
physics: NeverScrollableScrollPhysics(),
child: Form(
child: Column(
children: <Widget>[
TextFormField(
controller: name,
maxLength: 40,
textAlign: TextAlign.left,
keyboardType: TextInputType.text,
autocorrect: false,
decoration: InputDecoration(
labelText: 'Name der Klausur: ',
border: OutlineInputBorder(),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Gib den Namen der Klausur ein!';
}
return null;
},
),
SizedBox(height: 20),
TextFormField(
controller: deadline,
maxLength: 8,
textAlign: TextAlign.left,
keyboardType: TextInputType.datetime,
autocorrect: false,
decoration: InputDecoration(
labelText: 'Deadline: ',
border: OutlineInputBorder(),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Gib das Datum der Klausur ein!';
}
return null;
},
),
SizedBox(height: 20),
DropDownFormField(
titleText: 'Priorität',
hintText: 'Bitte auswählen',
value: '',
dataSource: [
{
"display": "Niedrig",
"value": "Niedrig",
},
{
"display": "Mittel",
"value": "Mittel",
},
{
"display": "Hoch",
"value": "Hoch",
},
],
textField: 'display',
valueField: 'value',
),
SizedBox(height: 20),
],
),
),
),
actions: <Widget>[
FlatButton(
onPressed: () {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text(name.text),
);
}
);
},
child: Text('Save'),
color: Colors.blue,
),
FlatButton(
onPressed: () {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text(deadline.text),
);
}
);
},
child: Text('Save'),
color: Colors.blue,
),
],
);
});
}
When the keyboard opens, it collides with the textfields -> I get an error:
Bottom overflowed by 49 pixels.
What could be the issue?
I have tried everything but I got stuck here.
SingleChildScrollView or resizeToAvoidBottomPadding: false didnt help me. Maybe I don't know how to use them correctly.
For any help I would be happy.
Is it me, or can't I find the code for your login screen? The error is thrown because there isn't enough place for your widget on the screen. Are you using a ListView or a Column? With a ListView you can scroll so if there isn't enough room for the content the user can scroll down to see what isn't on the screen.
My main.dart has become quite lengthy, so I'm splitting it up into various other .dart files for maintainability.
My main app uses a Google Map object and I place various red location markers on it. Now, I have various FloatingActionButton() along the bottom - each one opens a Bottom Sheet, using showBottomSheet() or showModalBottomSheet().
The only way I can currently think to split the main app into various files (to keep tidy) is to have the contents of these various bottom sheets in different .dart files which then are called from the main.dart - probably the wrong way.
Main.dart
...
import 'package:flutter_app/db_manager.dart' as db_manager;
import 'package:flutter_app/section_about.dart';
import 'package:flutter_app/section_settings.dart';
void main() => runApp(MyApp());
SectionAbout sectionAbout = SectionAbout();
SectionSettings sectionSettings = SectionSettings();
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
GoogleMapController mapController;
static const LatLng _center = const LatLng(xxxxxxx, xxxxxxx);
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
}
void _onCameraMove(CameraPosition position) {
_lastMapPosition = position.target;
}
final Set<Marker> _markers = {};
MapType _currentMapType = MapType.normal;
LatLng _lastMapPosition = _center;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My Map'),
backgroundColor: Colors.green[700],
),
//Put in a stack widget so can layer other widgets on top of map widget
body: Stack(
children: <Widget>[
GoogleMap(
mapType: _currentMapType,
markers: _markers,
onMapCreated: _onMapCreated,
onCameraMove: _onCameraMove,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Align(
alignment: Alignment.bottomCenter,
child: Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
SizedBox(width: 16.0),
Builder(
builder: (context) => FloatingActionButton(
child: Icon(Icons.settings, size: 36.0),
backgroundColor: Colors.green,
onPressed: () {
sectionSettings.onSheetShowContents(context); <------
}),
),
SizedBox(width: 16.0),
FloatingActionButton(
onPressed: _onDownloadTestPressed,
materialTapTargetSize: MaterialTapTargetSize.padded,
backgroundColor: Colors.green,
child: const Icon(Icons.autorenew, size: 36.0),
),
SizedBox(width: 16.0),
Builder(
builder: (context) => FloatingActionButton(
child: Icon(Icons.help, size: 36.0),
backgroundColor: Colors.green,
onPressed: () {
sectionAbout.onSheetShowContents(context); <------
}),
),
SizedBox(width: 16.0),
FloatingActionButton(
onPressed: _onDBActions,
materialTapTargetSize: MaterialTapTargetSize.padded,
backgroundColor: Colors.green,
child: const Icon(Icons.change_history, size: 36.0),
),
])),
),
],
),
),
);
}
}
Settings.dart
import 'package:flutter/material.dart';
import 'package:flutter_app/db_manager.dart' as db_manager;
class SectionSettings {
int mapTypeView = 0;
void onSheetShowContents(Context context) {
showModalBottomSheet(
//showBottomSheet(
context: context,
builder: (context) {
return ListView(
padding: EdgeInsets.all(15.0),
children: <Widget>[
ListTile(
title: Text("Map Settings"),
selected: true,
),
Divider(),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: [
Column(
children: <Widget>[
Text("Map View"),
],
),
Column(
children: <Widget>[
Row(
children: <Widget>[
ChoiceChip(
label: Text("Normal Map"),
selected: mapTypeView == 0,
onSelected: (value) {
setState(() {
mapTypeView = 0;
_currentMapType =
MapType.normal;
});
},
),
SizedBox(width: 8),
ChoiceChip(
label: Text("Satelite Map"),
selected: mapTypeView == 1,
onSelected: (value) {
setState(() {
mapTypeView = 1;
_currentMapType =
MapType.satellite;
});
},
),
],
),
],
)
],
),
],
// ),
);
});
}
}
Notice how I use <OtherDartFileName>.onSheetShowContents(); and that code is moved to <OtherDartFileName> rather than have a huge section here in the main dart file.
This has introduced a problem, where I cannot modify the State of the Google Map from within this Bottom Sheet as it has no reference (and I can't seem to pass one along) of the main app state.
I want to have a Bottom Sheet that contains a button that toggles Normal View and Satellite View on the main Map (and eventually other options)
Have I structured this project completely incorrectly, or can I just reference the Map state somehow?
I also have separate .dart files for one SQFlite instance and managing all DB operations. Coding for android and will be pushing to iOS eventually.
Many thanks
I've started playing with Flutter a little bit.
I created a page, that looks like this:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:smooth_star_rating/smooth_star_rating.dart';
import 'package:intl/intl.dart';
class LandOffer extends StatefulWidget {
final String startPoint;
final String endPoint;
const LandOffer({Key key, this.startPoint, this.endPoint}) : super(key: key);
#override
State<StatefulWidget> createState() {
return _LandOffer(startPoint: this.startPoint, endPoint: this.endPoint);
}
}
class _LandOffer extends State<LandOffer> {
final String startPoint;
final String endPoint;
var _json;
String _name;
String _lastName;
String _image;
var isLoading = false;
_fetchBackendData() async {
setState(() {
isLoading = true;
print('Beginning loading');
});
final response =
await http.get("https://randomuser.me/api/?inc=name,picture");
if (response.statusCode == 200) {
_json = json.decode(response.body);
setState(() {
isLoading = false;
_name = toBeginningOfSentenceCase(_json['results'][0]['name']['first']);
_lastName =
toBeginningOfSentenceCase(_json['results'][0]['name']['last']);
_image = _json['results'][0]['picture']['large'];
print('Done loading...');
});
} else {
throw Exception('Failed to load backend data');
}
}
#override
void initState() {
super.initState();
_fetchBackendData().then((result) {
print('Feched data from backend');
});
}
_LandOffer({this.startPoint, this.endPoint});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Describe your offer '),
automaticallyImplyLeading: true,
),
body: isLoading
? Center(
child: CircularProgressIndicator(),
)
: ListView(
children: <Widget>[
Column(
children: <Widget>[
Row(
children: <Widget>[
Image(
image: NetworkImage(_image),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'First name: $_name',
textAlign: TextAlign.left,
),
Text(
'Last name: $_lastName',
textAlign: TextAlign.left,
),
Text('Rating'),
SmoothStarRating(
rating: 3.2,
),
],
),
],
),
],
),
],
));
}
}
which in additions displays the image like this:
But it seems like there is a padding added to a text.
I would like to move the text to the very top, and add a padding, should I need one.
Also, if I apply the padding to the image, it applies the padding to the whole row, which is not the desired result.
Thank you in advance for your help.
Because your image height are bigger one in row, if you add padding(assume both top,bottom,left,right) to image, the row height will be expanded too. Unless you only want padding(left, right) or you need constraint image height.
Row(
crossAxisAlignment: CrossAxisAlignment.start, //<-- move text top
children: <Widget>[
Padding(
padding: EdgeInsets.all(5),
child: Image(
image: NetworkImage(_image),
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start, //<-- move text top
children: <Widget>[
Text(
'First name: $_name',
textAlign: TextAlign.left,
),
Text(
'Last name: $_lastName',
textAlign: TextAlign.left,
),
Text('Rating'),
SmoothStarRating(
rating: 3.2,
),
],
),
],
),
I am developing a flutter app, but it show error when I run the app.
I don't understand what is the problem. I think I mix up the logic of how the widget expand in layout.
Please kindly help to solve this issue.
error message:
flutter: The following assertion was thrown during performResize():
flutter: Vertical viewport was given unbounded height.
Viewports expand in the scrolling direction to fill their container.In this case, a vertical
viewport was given an unlimited amount of vertical space in which to expand. This situation
typically happens when a scrollable widget is nested inside another scrollable widget.
Here with my code:
body: Container(
child: Flexible(
child: FirebaseAnimatedList(
query: databaseReference,
itemBuilder: (_, DataSnapshot snapshot,
Animation<double> animation,
int index) {
return new Card(
color: Colors.black38,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ListTile(
leading: IconButton(
icon: Icon(Icons.format_list_bulleted),
color: Colors.blueAccent,
splashColor: Colors.greenAccent,
onPressed: () {
// Perform some action
debugPrint('button ok');
},
),
title: Text(shopList[index].shopName),
subtitle: Text(shopList[index].address),
),
Container(
child: Flexible(
child: Form(
key: formShopKey,
child: ListView(
children: <Widget>[
ListTile(
leading: Icon(
Icons.money_off,
color: Colors.white,
),
title: TextFormField(
maxLength: 100,
initialValue: "",
maxLines: 3,
//onSaved: (val) => booking.seafoodRequest = val,
//validator: (val) => val == "" ? val : null,
decoration: new InputDecoration(
),
),
),
],
),
),
),
),
ButtonTheme.bar(
// make buttons use the appropriate styles for cards
child: new ButtonBar(
children: <Widget>[
new FlatButton(
child: const Text('BUY TICKETS'),
onPressed: () {
/* ... */
},
),
new FlatButton(
child: const Text('LISTEN'),
onPressed: () {
/* ... */
},
),
],
),
),
],
),
);
},
),
),
);
[1]: https://i.stack.imgur.com/5vAsv.png
[2]: https://i.stack.imgur.com/LuZEl.png
I had to fill in a few gaps but the below should build for you. I also swapped FirebaseAnimatedList with a regular AnimatedList to get it to build. You can compare and adjust the layout.
import 'package:flutter/material.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: 'Flutter Demo'),
);
}
}
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(
body: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Expanded(
child: AnimatedList(
initialItemCount: 10,
itemBuilder: (BuildContext context, int index,
Animation<double> animation) {
return new Card(
color: Colors.black38,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ListTile(
leading: IconButton(
icon: Icon(Icons.format_list_bulleted),
color: Colors.blueAccent,
splashColor: Colors.greenAccent,
onPressed: () {
// Perform some action
debugPrint('button ok');
},
),
title: Text('Name'),
subtitle: Text('Address'),
),
Container(
constraints: BoxConstraints(
minHeight: 100.0,
maxHeight: 200.0,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Expanded(
child: Form(
child: ListView(
children: <Widget>[
ListTile(
leading: Icon(
Icons.money_off,
color: Colors.white,
),
title: TextFormField(
maxLength: 100,
initialValue: "",
maxLines: 3,
//onSaved: (val) => booking.seafoodRequest = val,
//validator: (val) => val == "" ? val : null,
decoration: new InputDecoration(),
),
),
],
),
),
),
],
),
),
ButtonTheme.bar(
// make buttons use the appropriate styles for cards
child: new ButtonBar(
children: <Widget>[
new FlatButton(
child: const Text('BUY TICKETS'),
onPressed: () {
/* ... */
},
),
new FlatButton(
child: const Text('LISTEN'),
onPressed: () {
/* ... */
},
),
],
),
),
],
),
);
},
),
),
],
),
);
}
}