我有两个飞镖页。 [1]:https://i.stack.imgur.com/D1xaf.png
在第二页中,我从网站上抓取文字并将值存储在名为fetchedstring
的字符串中,并在控制台命令行中打印字符串使用命令print
。
但我想在主要飞镖页中显示此字符串。
怎么做?
//DART FILE 1 HAS THE FOLLOWING CODE
import 'package:flutter/material.dart';
import './function.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget
{
@override
Widget build(BuildContext context)
{
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(),
body: new Center(
child: new String(fetchedtext),//Here I Want The Fetched Text
),
),
);
}
}
//DART PAGE 2 HAS THE FOLLOWING CODE
import 'package:http/http.dart' as http;
import 'package:html/parser.dart' as parser;
import 'package:html/dom.dart';
mainz() async
{
http.Response response = await http.get('https://www.google.com');
Document document = parser.parse(response.body);
document.getElementsByTagName('a').forEach((Element element)
{
final String fetchedText = element.text;
print(fetchedText);
}
);
}
//I WANT THAT String "fetchedtext" to be displayed in my Dart Page1.
答案 0 :(得分:0)
如果我对您尝试做的事情的理解是正确的,那么您需要将其粘贴到function.dart
文件的最后:
List get_elements() {
http.Response response = await http.get('https://www.google.com');
Document document = parser.parse(response.body);
document.getElementsByTagName('a').forEach((e) => print(e));
return document.getElementsByTagName('a');
}
然后修改main.dart
中的一行:
child: get_elements().first;
请注意,如果您不想返回找到的第一个元素,请先删除并使用[]选择要获取的元素,或者如果要获取整个列表,只需删除{{1}但是,你会得到一个字符串。
答案 1 :(得分:0)
import 'package:flutter/material.dart';
import 'dart:async';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget
{
@override
Widget build(BuildContext context)
{
var builder = FutureBuilder(
future: mainz(),
builder: (context, snapshot) {
if (snapshot.hasError) {
print(snapshot.error);
return new Text("${snapshot.error}");
}
return snapshot.hasData
? new Center(
child: Text(snapshot.data), //Here I Want The Fetched Text
)
: new CircularProgressIndicator();
},
);
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text("Title"),
),
body: builder,
)
);
}
}
Future<String> mainz() async
{
await new Future.delayed(new Duration(seconds: 3));
return 'Sample data';
}