How can I justify text with Flutter markdown? - flutter

I started using flutter markdown, however I'd like to justify the content, and I couldn't until now.
I tried using a Center and Alignment but didn't work.
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
class OutsideBankHourDescription extends StatelessWidget {
#override
Widget build(BuildContext context) {
String text =
"Antecipações em __horários__ bancários acontecem em 1h na média. __Fora do horário bancário__ o saldo estará em sua conta __no dia seguinte.__";
return Expanded(
child: Container(
alignment: Alignment.center,
child: Markdown(
styleSheet: MarkdownStyleSheet.fromTheme(Theme.of(context)),
data: text,
),
),
);
}
}

It's not available for now to change text alignment in flutter_markdown 0.2.0.
You must contact the authors of this plugin to request this feature.
But if you need fast fix, you can add textAlign: TextAlign.center attribute in source code of this file: https://github.com/flutter/flutter_markdown/blob/master/lib/src/builder.dart
Line of code: 345
mergedTexts.add(new RichText(text: mergedSpan, textAlign: TextAlign.center));
Result:
For more elegant way you must clone git repository of this plugin, attach to your project directly and work to add text alignment feature on your own.

It becomes possible to set up proper text alignment with flutter_markdown.
var style = MarkdownStyleSheet(
textAlign: WrapAlignment.center,
h1Align: WrapAlignment.center,
);
Markdown(
styleSheet: style,
data: '# header1 is center-aligned\ntext body is also center-aligned'
);
You can customized your styles with all the other optional parameters provided by MarkdownStyleSheet class.

Related

Pie Chart disappears when "defaultRenderer: charts.ArcRendererConfig" is added to Charts in Flutter

I am completely new to Flutter, but I need to develop a mobile app for a university project using Flutter & Dart. I want to add a Pie Chart to my application and so I imported the flutter_charts package. I have gotten it to sort of work. Below is the code currently which produces a working result.
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:sa_voting_app/Charts/main_series.dart';
class VoterChart extends StatelessWidget {
const VoterChart({Key? key, required this.data}) : super(key: key);
final List<VoterSeries> data;
#override
Widget build(BuildContext context) {
List<charts.Series<VoterSeries, String>> series = [
charts.Series(
id: "Voters",
data: data,
domainFn: (VoterSeries series, _) => series.party,
measureFn: (VoterSeries series, _) => series.voters,
colorFn: (VoterSeries series, _) => series.barColor)
];
return Container(
height: MediaQuery.of(context).size.height,
padding: const EdgeInsets.all(20),
child: SizedBox(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Text(
"Current Leader Board for Parties:",
style: Theme.of(context).textTheme.bodyText1,
),
Expanded(
child: charts.PieChart(series,animate: true),
),
],
),
),
),
),
);
}
}
It produces the following output:
I want to then add labels to the PieChart. So I googled a few tutorials and came up with this code:
Expanded(
child: charts.PieChart(series,
defaultRenderer: charts.ArcRendererConfig(
customRendererId: 'mainChartRender',
arcRendererDecorators: [
charts.ArcLabelDecorator(
labelPosition: charts.ArcLabelPosition.inside),
],
),
animate: true),
),
However as soon as I add this code and try to run my application again the following happens:
As you can see the Chart dissapears, I also get an exception in the box.dart file which appears as follows:
This is the code where the exception appears:
Size get size {
assert(hasSize, 'RenderBox was not laid out: ${toString()}');
assert(() {
final Size? _size = this._size;
if (_size is _DebugSize) {
assert(_size._owner == this);
if (RenderObject.debugActiveLayout != null &&
!RenderObject.debugActiveLayout!.debugDoingThisLayoutWithCallback) {
assert(
debugDoingThisResize || debugDoingThisLayout || _computingThisDryLayout ||
(RenderObject.debugActiveLayout == parent && _size._canBeUsedByParent),
'RenderBox.size accessed beyond the scope of resize, layout, or '
'permitted parent access. RenderBox can always access its own size, '
'otherwise, the only object that is allowed to read RenderBox.size '
'is its parent, if they have said they will. It you hit this assert '
'trying to access a child\'s size, pass "parentUsesSize: true" to '
"that child's layout().",
);
}
assert(_size == this._size);
}
return true;
}());
return _size!;
}
I have tried looking at various places online to try and get a solution, but most stuff that references the "Render Box was not laid out error" is in regards to putting a ListView/GridView into a Column/Row. There was two of the following posts that reference similar issues: Flutter GoogleChart Pie chart does not render (I followed the very few solutions suggested here, but none yielded results.) There was also this post, but again its suggested solutions did not fix my issue.
Being new to Flutter I do not have any idea where to even begin troubleshooting. I would greatly appreciate it if someone could guide me in the right direction or help explain what exactly is causing the error. Thank you very much in advance for your time.
I faced similar issue as well.
I don't know why but it happens when we use defaultRenderer
After searching on google a bit I found a work around.
I don't know why it works, but it worked in my case at least.
Here is link to Source
You have to add the type parameter of the PieChart
so as you have series of type charts.Series<VoterSeries, String>> you updated code should look like
Expanded(
child: charts.PieChart<String>(series,
defaultRenderer: charts.ArcRendererConfig(
customRendererId: 'mainChartRender',
arcRendererDecorators: [
charts.ArcLabelDecorator(
labelPosition: charts.ArcLabelPosition.inside),
],
),
animate: true),
),
Notice a type parameter <String> is added in
child: charts.PieChart<String>(series,
Hope it helps.

How can I edit a text and add photo on illustrator image in flutter?

cv template and I want to edit it with flutter
Everything in Flutter is widgets, this image would be an Image widget in your Flutter app.
You can use Stack widget to put things over each other. so You can put image over an image by using Stack widget.
Unfortunately you can't edit text of an image in Flutter, Instead I would rather to edit this image (for putting image and editing text) by Photoshop for example and then implementing it as one piece widget in my Flutter app.
What I assess from your question is you want to have a layout like the one given in your link, right? For a circular image, you could use CircleAvatar. As for the text you could use the Text widget. Now put these widgets inside a Column or Row. You seem to be new to Flutter and I'd suggest you to get a good grip on the basics first. Anyhow, here's a little dummy code snippet you could extend to achieve what you're looking for
Column(
crossAxisAlignment: CrossAxisAlignment
.start, //if you want your widgets to align on left in your col
children: [
CircleAvatar(
radius: 70,
foregroundImage: AssetImage("pathToYourAssetImg"),
),
SizedBox(
height: 20, //set this to your intended value
),
Text( //you could also create a custom text widget and pass the arguments if you don't want to hardcode text widgets over & over again for all of your text
"yourText",
style: TextStyle(
color: Colors.black87,
fontSize: 20, //set this to your value
fontWeight: FontWeight.bold //if you want to have a bold text
),
),
],
);

How to add SVGs to AppBar class in Flutter?

I'd like to be able to add an svg image to the AppBar in my flutter application. I've used a package called flutter_svg to add the svgs to the project, however the images do not appear in the project. The code in the main is as follows:
class FrontpageState extends State<Frontpage> {
//mother widget
Widget build(BuildContext context) {
final Widget svgJuro = SvgPicture.asset(juro);
final Widget svgBanco = SvgPicture.asset(banco, semanticsLabel: 'Banco');
final Widget svgGoverno =
SvgPicture.asset(titulos, semanticsLabel: 'Titulos');
final Widget svgFundos = SvgPicture.asset(fundos, semanticsLabel: 'Fundos');
final Widget svgQuestao =
SvgPicture.asset(questao, semanticsLabel: 'Questão');
return Scaffold(
appBar: AppBar(
shadowColor: jBrown100,
title: Align(
alignment: Alignment(-0.6, 0),
child: Text('JURAS?',
style: GoogleFonts.roboto(
color: jBlack100,
fontSize: 48,
fontWeight: FontWeight.w700,
letterSpacing: -2))),
actions: [
new IconButton(icon: svgJuro, onPressed: null, color: jPink100)
],
));
}
The code in the dependencies and a separate assets dart file:
dependencies:
flutter:
sdk: flutter
google_fonts: ^1.1.1
flutter_svg: ^0.19.1
//assets.dart
final String juro = 'imgAsset/juro.svg';
final String banco = 'imgAsset/banco.svg';
final String titulos = 'imgAsset/governo.svg';
final String fundos = 'imgAsset/fundos.svg';
final String questao = 'imgAsset/questao.svg';
I put the SVG in the actions because I want to animate the SVG in the future. I think the only way I can achieve this is through a custom appbar using a container, here is the design I am trying to implement, please give me any suggestions regarding making this design a reality:
Thank you in advance for your help.
Just make sure that your images are .svg format [use a convertor to convert to .svg format]. I had a similar issue as the one mentioned when trying to display a .png image.
1.Enable Custom assets. Then move your svg file to assets folder.
2.Run this command:
With Flutter:
$ flutter pub add flutter_svg
3.Now in your Dart code, you can use:
import 'package:flutter_svg/flutter_svg.dart';
4.Code Like This:
title: SvgPicture.asset('./assets/traveler.svg'),

Using space left by siblings in a row - MediaQuery.of(): context is null

I'm trying to arrange two texts in a row. The second text is only a few words, but the first can be very long. My goal is to show the second text fully, and fill the remaining space with the first. If the first widget is too wide, I want to truncate it with an ellipsis.
Expected layout:
My code is
class MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
GlobalKey key = GlobalKey();
return Row(
children: [
Container(
child: Text("Really really really long long long teeeeext",
maxLines: 1,
overflow: TextOverflow.ellipsis),
width: MediaQuery.of(context).size.width - MediaQuery.of(key.currentContext).size.width),
Text("short text", key: key)
],
);
}
}
It fails with The following assertion was thrown building MyHomePage(dirty, dependencies: [MediaQuery]): I/flutter (28083): 'package:flutter/src/widgets/media_query.dart': Failed assertion: line 810 pos 12: 'context != I/flutter (28083): null': is not true.
I guess because the Flutter engine hasn't started rendering the "short text" widget yet, so it's size is unknown at this time.
Any help will be appreciated.
What if you try to init your second Text Widget like Text _secondText=Text("short text")? So Flutter should already know its content when you use your first widget. You can give it a try.
MediaQuery.of(context).size isn't available during build phase. While building the widget, sizes aren't calculated yet.
However you don't need MediaQuery.of(context).size to implement the layout. Instead, you can simply wrap left text with Expanded. Then it will take all remaining space (total width minus right text width).
Row(
children: [
Expanded(
child: Text(
"Really really really long long long teeeeext 123 123 123 123 123 123 123 123",
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
Text(
"short text",
),
],
)
Result:

Starting with plain (non material ui) canvas in flutter

All tutorials and documentation I've seen so far start of with importing flutter material. I am wondering is this an absolute requirement? What if I want to start with a plain canvas and build my own theme / widgets. Can I do this, if so what package should be used here so I get access to default widgets?
Although the answers here are correct, I want to add a few more points. To use raw widgets use import 'package:flutter/widgets.dart';
Here is a working example:
import 'package:flutter/widgets.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(25.0),
child: Directionality(
textDirection: TextDirection.ltr,
child:Text("hello world",
style: TextStyle(
color: Color.fromRGBO(255, 255, 255, 1)
),
)));
}
}
The directionality is needed, the padding was added so that we see the message, otherwise it is masked by the menubar in phone.
Widgets in flutter makes the developers day easy. All the widgets are built on top dart:ui lib. It is up to you, to decide to use existing set of widgets or develop your ui from scratch. Flutter does not stop you from writing your own widgets.
You can find a few raw example of here, that does not use any widgets at all.
If you simple don't want only material widgets, then you can just build your own themed widgets with all other basic widgets and layouts available in flutter.
If you wanted to build few of your own widgets with a canvas and use it along with other widgets in flutter, you look into CustomPaint and CustomPainter widgets.
Hope this helped!
Just as Chandan Purohit answered, use import 'package:flutter/widgets.dart';. Flutter official gives a minimal app in Introduction to widgets as follows:
import 'package:flutter/material.dart';
void main() {
runApp(
const Center(
child: Text(
'Hello, world!',
textDirection: TextDirection.ltr,
),
),
);
}
Just change flutter/material.dart to flutter/widgets.dart, and you get a plain canvas to start.
Note: The color of Text is white by default.