Related
I'm using a StreamProvider to capture changes that occur in Firestore and display them on the user homepage. When the user initially signs in or registers, they're directed to this homepage and expect to see their details, for which I use the StreamProvider.
Keeping in mind that the first value fetched will be null, I've added a Loading Text Widget. However, the widget does not seem to change unless I hot-refresh the page and the Stateful Widget gets rebuilt again.
What seems to be happening is that the Stateful Widget I'm using as my HomePage gets "built" only once due to which even when the stream gets populated with non-null values, the loading widget does not disappear because its parent widget doesn't get rebuilt.
This is the basic HomeScreen widget around which I'm wrapping my StreamProvider.
#Override
Widget build(BuildContext context) {
return StreamProvider<UserDataModel>.value(
initialData: null,
value: DatabaseServices(userDetails: _userDetails).userDataDocument,
updateShouldNotify: (previous, current) => true,
child: Scaffold(
backgroundColor: Colors.white,
body: HomeBody(),
)
);
}
This is the relevant snippet from the HomeBody widget
class HomeBody extends StatefulWidget {
#override
_HomeBodyState createState() => _HomeBodyState();
}
class _HomeBodyState extends State<HomeBody> {
#override
Widget build(BuildContext context) {
final AuthenticationServices _authServices = AuthenticationServices();
final UserDataModel _data = Provider.of<UserDataModel>(context);
print(_data);
print((_data != null) ? _data.name : 'NULL');
/* Some code */
Row(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(25, 0, 0, 5),
child: Text(_data != null ? _data.name : 'LOADING...', style: dashboardName),
),
],
),
Row(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(25, 2, 0, 5),
child: Text(_data != null ? _data.scholarId : 'LOADING...', style: dashboardName),
),
],
),
I also noticed that the print statements I've used for debugging get executed only once printing those initial null values, until, I hot-refresh the page and the non-null values are shown.
Is there a way to go around this? I've been stuck for a couple of days now without making any significant advances and any sort of guidance would be appreciated.
I've been trying to use charts_flutter prepared by google team in flutter. I was trying to use stacked bar charts and I was following this Stacked Bar Charts Demo. But, there is a tweak I want for my requirements. But, I couldn't figure out how to do it?.
Following is my code.
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
class WeighAbleStatsScreenV3 extends StatefulWidget {
#override
_WeighAbleStatsScreenV3State createState() => _WeighAbleStatsScreenV3State();
}
class _WeighAbleStatsScreenV3State extends State<WeighAbleStatsScreenV3> {
List<charts.Series> seriesList;
/// Create series list with multiple series
static List<charts.Series<OrdinalSales, String>> _createSampleData() {
final desktopSalesData = [
OrdinalSales('2014', 25),
OrdinalSales('2015', 28),
OrdinalSales('2016', 26),
OrdinalSales('2017', 30),
];
final tableSalesData = [
OrdinalSales('2014', 3),
OrdinalSales('2015', 3),
OrdinalSales('2016', 2),
OrdinalSales('2017', 2),
];
final mobileSalesData = [
OrdinalSales('2014', 5),
OrdinalSales('2015', 4),
OrdinalSales('2016', 4),
OrdinalSales('2017', 2),
];
return [
charts.Series<OrdinalSales, String>(
id: 'Desktop',
domainFn: (OrdinalSales sales, _) => sales.year,
measureFn: (OrdinalSales sales, _) => sales.sales,
data: desktopSalesData,
),
charts.Series<OrdinalSales, String>(
id: 'Tablet',
domainFn: (OrdinalSales sales, _) => sales.year,
measureFn: (OrdinalSales sales, _) => sales.sales,
data: tableSalesData,
),
charts.Series<OrdinalSales, String>(
id: 'Mobile',
domainFn: (OrdinalSales sales, _) => sales.year,
measureFn: (OrdinalSales sales, _) => sales.sales,
data: mobileSalesData,
),
];
}
#override
void initState() {
super.initState();
seriesList = _createSampleData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
height: 500,
child: charts.BarChart(
seriesList,
animate: true,
barGroupingType: charts.BarGroupingType.stacked,
),
),
),
);
}
}
/// Sample ordinal data type.
class OrdinalSales {
final String year;
final int sales;
OrdinalSales(this.year, this.sales);
}
Output :
Charts are working fine. But, I want Y-axis to be dynamic and non-zero. For example, minimum value for charts data in my case is 25. So, my y-axis values should be 25-35 instead of starting from 0-35.
I do not want zero as starting point for my Y-axis values. But, I couldn't add non-numeric values or values above zero.
Also, It's best if I can add string values to my Y-axis as well?
I've followed documentation thoroughly. But, couldn't find anything.
Any help would be appreciated.
Thanks.
I have read your question and I've checked out the flutter charts documentation and It seems your requirements are not supported by official chart_flutter package.
As Non-zero Y-axis kind of features are mainly supported in line charts but not in bar charts.
Also, there is one more package flutter_charts which is not too famous. But, it will solve your use case.
This package has support for the feature of non-zero y-axis as well as non-numeric y-axis values.
Alternatively, you can also create your own bar charts using Stack and FractionallySizedBox for your stacked bar chart requirements.
You'll see a list of instructions when you select the third option:
Follow these instructions, and the command should output a output.zip file which you can upload. Not sure what's confusing about the instructions :)
I am using my android phone to run my flutter code. The problem is when i run any code(i.e. different from the auto generated flutter code that is created when i create a flutter project)it always shows me the output of the auto generated flutter code. I have to reload it after each run to get the output of my new code. Plus, after i detached my phone from my PC the app i get on my phone is still the auto generated one. I have used both android studio and VS code but the problem still persists. I have tried to create new project but still no luck.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() => runApp(new MaterialApp(home: new KeyetWedetApp ())); //The runApp() function takes the given Widget and makes it the root of the widget tree.
class KeyetWedetApp extends StatefulWidget {
#override
_State createState() => new _State();
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.red,
),
home: new KeyetWedetApp(),
darkTheme: new ThemeData(accentColor: Colors.deepPurpleAccent),
);
}
}
class _State extends State<KeyetWedetApp> {
static List _pageSelectorList = <Widget>[
Image.asset('assets/images/balloon.jpeg'),
Image.asset('assets/images/beach.jpeg'),
Image.asset('assets/images/camp.jpeg'),
Image.asset('assets/images/hello.png'),
Image.asset('assets/images/mountain.jpeg')
//TODO Insert our own images which describe what our application will do step by step.
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: new Container(
child: new DefaultTabController(
length: _pageSelectorList.length,
child: Builder(
builder: (BuildContext context) => Padding(
padding: EdgeInsets.fromLTRB(10.0, 30.0, 10.0, 10.0),
child: new Column(
children: <Widget>[
new TabPageSelector(selectedColor: Colors.blue),
new Expanded(
child: IconTheme(
data: IconThemeData(
size: 200.0,
color: Theme.of(context).accentColor,
),
child: TabBarView(
children: _pageSelectorList,
),
)),
new FlatButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage()));
},
child: new Text(
'Let\'s Get Started',
style: new TextStyle(fontSize: 20, color: Color(0xFF757575)),
),
)
],
),
),
),
),
),
),
);
}
}
When i run the this code, it compile and run normally without error or exceptions. It goes like this:
Launching lib\main.dart on SM G950F in debug mode...
√ Built build\app\outputs\apk\debug\app-debug.apk.
D/FlutterActivity( 9631): Using the launch theme as normal theme.
D/FlutterActivityAndFragmentDelegate( 9631): Setting up FlutterEngine.
D/FlutterActivityAndFragmentDelegate( 9631): No preferred FlutterEngine was provided. Creating a new FlutterEngine for this FlutterFragment.
D/FlutterActivityAndFragmentDelegate( 9631): Attaching FlutterEngine to the Activity that owns this Fragment.
D/FlutterView( 9631): Attaching to a FlutterEngine: io.flutter.embedding.engine.FlutterEngine#133f78d
D/FlutterActivityAndFragmentDelegate( 9631): Executing Dart entrypoint: main, and sending initial route: /
D/ViewRootImpl#bcf80b7MainActivity: MSG_RESIZED_REPORT: frame=Rect(0, 0 - 1080, 2220) ci=Rect(0, 63 - 0, 0) vi=Rect(0, 63 - 0, 0) or=1
D/InputTransport( 9631): Input channel constructed: fd=99
D/InputMethodManager( 9631): prepareNavigationBarInfo() DecorView#13938bf[MainActivity]
D/InputMethodManager( 9631): getNavigationBarColor() -855310
V/InputMethodManager( 9631): Starting input: tba=com.keyetwedet.keyet_wedet ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
D/InputMethodManager( 9631): startInputInner - Id : 0
E/AccessibilityBridge( 9631): VirtualView node must not be the root node.
And when it finally launches the code on my phone, no matter what code i wrote, it always show the flutter sample code output like this:
This is what i always get on the first run
So, in order to get my phone showing my code i have to "hot restart" it. Only then i will get the output of my code.
This is my code's output which comes after i hot restarted it
But after i stopped the debugging and detached my phone from my PC, the app i get on my phone is still the output of the flutter sample code.
In summary my questions are the following:
Why isn't it showing my code's output on the first run.
Why isn't it saving my code on my device so that when i open the app on my phone it could show me the output of my code.
I'm also facing the same issue. But I found what went wrong.
Problem:
I didn't save the code after making changes in default example.
Solution:
Press CTRL+s to save each time any change is made in code.
Preferred solution:
Go to menu in Visual Studio Code, File -> Click 'Auto save'. So that you don't have to save changes each time, it will be auto-saved.
I tried many things and found out that if I run flutter clean on the terminal before going into debugging it solves the problem!
How to show html tag string in flutter, i have tried a plugin and its not working.
new HtmlView(
data: html,
baseURL: "", // optional, type String
onLaunchFail: (url) { // optional, type Function
print("launch $url failed");
}
This is my html
“Follow<a class='sup'><sup>pl</sup></a> what was sent down to you from your Lord, and do not follow other guardians apart from Him. Little do <span class='h'>you remind yourselves</span><a class='f'><sup f=2437>1</sup></a>.”
i user flutter_html_view: "^0.5.10" this plugin
This plugin doesn`t have any issue, I just created a sample with your HTML and it works fine. Try to replace with below snippet and see if that works.
dependencies:
flutter_html: ^0.8.2
and imports and code to render html
import 'package:flutter_html/flutter_html.dart';
import 'package:html/dom.dart' as dom;
body: new Center(
child: SingleChildScrollView(
child: Html(
data: """
<div>Follow<a class='sup'><sup>pl</sup></a>
Below hr
<b>Bold</b>
<h1>what was sent down to you from your Lord</h1>,
and do not follow other guardians apart from Him. Little do
<span class='h'>you remind yourselves</span><a class='f'><sup f=2437>1</sup></a></div>
""",
padding: EdgeInsets.all(8.0),
onLinkTap: (url) {
print("Opening $url...");
},
customRender: (node, children) {
if (node is dom.Element) {
switch (node.localName) {
case "custom_tag": // using this, you can handle custom tags in your HTML
return Column(children: children);
}
}
},
),
),
)
I've just done the followings and it works fine.
Add flutter_html to your pubspec.yaml file.
dependencies:
flutter:
sdk: flutter
flutter_html: ^0.8.2
Run the following command to update packages.
flutter pub get
Import flutter_html
import 'package:flutter_html/flutter_html.dart';
Replace Text widget with Html widget.
child:
// Text(
// "Hello Programmer",
// style: TextStyle(fontSize: 18),
// ),
Html(data:"<p>Hello <b>Flutter</b><p>"),
Do not use flutter_html_view that reading at the documentation:
Supported Tags
p
em
b
img
video
h1,
h2,
h3,
h4,
h5,
h6
Note
This plugin converts some of the html tags to flutter widgets This plugin does't support rendering full html code (there is no built in
support for web rendering in flutter)
So it simply doesn't render well your html because it can't.
But you could find other pulugins, like flutter_html
https://github.com/Sub6Resources/flutter_html
and give them a try in order to see if they perform better.
UPDATE
In pubspec.yaml I've add
dependencies:
flutter_html: ^0.8.2
and my main.dart is
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
var html = "Follow<a class='sup'>pl</a> what was sent down to you from your Lord, and do not follow other guardians apart from Him. Little do <p class='h'>you remind yourselves</p><a class='f'><sup f=2437>1</a>.";
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Html(
data: html,
),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Add the following to your pubspec.yaml file:
dependencies:
flutter_html:
Currently Supported HTML Tags:
a, abbr, acronym, address, article, aside, b, bdi, bdo, big, blockquote, body, br, caption, cite, code, data, dd, del, dfn, div, dl, dt, em, figcaption, figure, footer, h1, h2, h3, h4, h5, h6, header, hr, i, img, ins, kbd, li, main, mark, nav, noscript, ol, p, pre, q, rp, rt, ruby, s, samp, section, small, span, strike, strong, sub, sup, table, tbody, td, template, tfoot, th, thead, time, tr, tt, u, ul, var
Example Usage:
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
new Html(
data: "<b>Welcome</b>,
defaultTextStyle: TextStyle(fontSize: 15),
),
],
)
all the packages mentioned from other answers are no longer maintained ( at least when I write this answer), it will create conflict to other packages I use which has recent update, I end up using this package: flutter_widget_from_html (ps: it is not mine)
Use flutter_webview_plugin plugin
example:
new WebviewScaffold(
url: new Uri.dataFromString('<html><body>hello world</body></html>', mimeType: 'text/html').toString()
Webview inside custom Rectangle
final flutterWebviewPlugin = new FlutterWebviewPlugin();
flutterWebviewPlugin.launch(url,
fullScreen: false,
rect: new Rect.fromLTWH(
0.0,
0.0,
MediaQuery.of(context).size.width,
300.0,
),
);
In the pubspec.yml add the following:
dependencies:
flutter_html:
Then run:
flutter clean && flutter pub get
Finally, add the code like this:
import 'package:flutter_html/flutter_html.dart';
.
.
.
body: Center( Html(
data: """
<div>This is the start of a div
<a class='sup'><sup>a sup</sup></a>
and after sub
<b>Bold</b>
<h1>This is a header with number 1557</h1>
A text and
<span class='h'>some stuff</div>
""",
),)
Until now, it works fine on both mobile and web.
might be a little late but i've made a project that accepts and tags
so you can do this
HTMLText('<b><i>SOME VERY IMPORTANT TEXT</i></b>');
and it'll translate your HTML into flutter based widgets and respect dark/light theme colors as well.
https://github.com/forumics/flutter-html-text
if you have list of object and need to groupBy you can use following link:
groupBy_in_flutter
I am trying to develop a flutter app. This flutter is creating teams for a card game. After the creation of the team, the points could be counted through the, so that you don't have to think about how many points everybody has.
But I got an exception, where I know where the exception and what it means, but i do not have any clue how i could solve the problem. I hope some of you guys could help me.
This is the code where the error is thrown:
import 'package:flutter/material.dart';
class Punktezaehler extends StatefulWidget{
final List<String> spieler_namen;
Punktezaehler(this.spieler_namen);
#override
State<StatefulWidget> createState() => new _Punktezaehler(this.spieler_namen);
}
class _Punktezaehler extends State<Punktezaehler>{
final List<String> spieler_namen;
_Punktezaehler(this.spieler_namen);
List<int> punkteanzahl_teamEins;
List<int> punkteanzahl_teamZwei;
#override
Widget build(BuildContext context) {
var spieler1 = spieler_namen[0].substring(0,3);
var spieler2 = spieler_namen[1].substring(0,3);
var spieler3 = spieler_namen[2].substring(0,3);
var spieler4 = spieler_namen[3].substring(0,3);
return new Scaffold(
appBar: new AppBar(
automaticallyImplyLeading: false,
title: new Text("$spieler1 & $spieler2 vs" +" $spieler3 & $spieler4"),
actions: <Widget>[
],
),
body: Container(
child: new Row(
children: <Widget>[
new Column(
children: <Widget>[
new IconButton(
icon: Icon(Icons.exposure_plus_2),
onPressed: () => punkte_hinzuzaehlen(1, 2)
)
],
),
new Column(
children: <Widget>[
//new FlatButton(onPressed: () => print(punkteanzahl_teamEins.length), child: new Text("Punkte")),
ListView.builder(
itemCount: punkteanzahl_teamEins.length, //--> Error is thrown here
itemBuilder: (context, index){
return Text(punkteanzahl_teamEins[index].toString());
}
),
new Row()
],
),
new Column(
children: <Widget>[
new IconButton(
icon: Icon(Icons.exposure_plus_2),
onPressed: () => punkte_hinzuzaehlen(2, 2)
)],
)
],
)
),
);
}
void punkte_hinzuzaehlen(int team, int nummer){
if (team == 1){
//Team 1 bekommt die Punkte
print("Team 1 gets points");
}
else if(team == 2){
//Team 2 bekommt die Punkte
print("Team 2 gets points");
}
}
}
And this is the error message:
══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter (26028): The following NoSuchMethodError was thrown while handling a gesture:
I/flutter (26028): The getter 'length' was called on null.
I/flutter (26028): Receiver: null
I/flutter (26028): Tried calling: length
After the fix, I got another error:
══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter (26028): The following assertion was thrown during performResize():
I/flutter (26028): Vertical viewport was given unbounded width.
I/flutter (26028): Viewports expand in the cross axis to fill their container and constrain their children to match
I/flutter (26028): their extent in the cross axis. In this case, a vertical viewport was given an unlimited amount of
I/flutter (26028): horizontal space in which to expand.
punkteanzahl_teamEins is only declared. But not initialized. So it is throwing null error.
You should assign value to punkteanzahl_teamEins as
List<int> punkteanzahl_teamEins = [1,4,5,7];
or pass data from parent as requirement.
We spend lost's of time to resolve issue finally we got a solution is: Please check you pubspec.yaml and remove extra '-' in case of assets file and also please follow the structure of that like spacing and all that.
We are must sure that issue only in pubspec.yaml file
First one check spieler_namen is null or not.If it is null then use below code i hope this will solve your problem.....
if(spieler_namen == null){
new Container(width: 10.0,height: 10.0,);
}else{
your requirement .......
}
In our case, we got this error when Internet Connection is off after calling webservice.
Initialize your list, and run hot restart (press R).
It works correctly.
If you called api in your project. check your device network connection. try to re start your simulator. that will fix this error.
I fix this by revisiting this section in pubspec.yaml
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
Ensure your spacing, hyphens and filenames are correct.
Note: You do not need to list every image file; instead, you can just list their directory:
assets:
- images/